<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Inquiry;
use App\Models\Seller;
use App\Models\Buyer;
use App\Models\Product;
use Faker\Factory as Faker;

class InquirySeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        $sellers = Seller::all();
        $buyers = Buyer::all();

        if ($sellers->isEmpty()) {
            $this->command->info('No sellers found. Skipping Inquiry seeding.');
            return;
        }

        foreach ($sellers as $seller) {
            // specific products for this seller
            $products = $seller->products;

            // Create 3-8 inquiries per seller
            for ($i = 0; $i < rand(3, 8); $i++) {
                $status = $faker->randomElement(['new', 'viewed', 'responded']);
                $buyer = $buyers->isNotEmpty() ? $buyers->random() : null;
                $product = $products->isNotEmpty() ? $products->random() : null;

                $inquiry = Inquiry::create([
                    'seller_id' => $seller->id,
                    'buyer_id' => $buyer ? $buyer->id : null,
                    'product_id' => $product ? $product->id : null,
                    'name' => $buyer ? $buyer->user->name : $faker->name,
                    'email' => $buyer ? $buyer->user->email : $faker->email,
                    'phone' => $faker->phoneNumber,
                    'message' => $faker->paragraph,
                    'status' => $status,
                    'created_at' => $faker->dateTimeBetween('-3 months', 'now'),
                ]);

                if ($status === 'viewed') {
                    $inquiry->update(['seller_viewed_at' => $faker->dateTimeBetween($inquiry->created_at, 'now')]);
                } elseif ($status === 'responded') {
                    $viewedAt = $faker->dateTimeBetween($inquiry->created_at, 'now');
                    $inquiry->update([
                        'seller_viewed_at' => $viewedAt,
                        'seller_response' => $faker->paragraph,
                        'responded_at' => $faker->dateTimeBetween($viewedAt, 'now'),
                    ]);
                }
            }
        }
    }
}
