<?php

namespace Database\Seeders\Demo;

use App\Models\Customers\Customer;
use App\Models\Geo\City;
use App\Models\People\SalesRep;
use Database\Seeders\Demo\Concerns\GeneratesDemoData;
use Illuminate\Database\Seeder;

class CustomerSeeder extends Seeder
{
    use GeneratesDemoData;

    private const CUSTOMER_COUNT = 75;

    private const ASSIGNED_REP_COUNT = 20;

    public function run(): void
    {
        $cityIds = City::inRandomOrder()->limit(60)->pluck('id')->all();
        $reps = SalesRep::all();

        for ($i = 1; $i <= self::CUSTOMER_COUNT; $i++) {
            $isBusiness = random_int(1, 100) <= 40;
            $name = $isBusiness ? $this->businessName() : fake()->name();

            $customer = Customer::create([
                'business_name' => $name,
                'phone' => $this->srPhone(),
                'nic' => $isBusiness ? null : $this->nic(),
                'email' => $isBusiness
                    ? strtolower(str_replace([' ', '(', ')'], '', $name)).'@business.lk'
                    : strtolower(str_replace(' ', '.', $name)).fake()->numberBetween(1, 999).'@gmail.com',
                'street_line1' => 'No. '.random_int(1, 300).', '.fake()->streetName(),
                'city_id' => fake()->randomElement($cityIds),
                'assigned_rep_id' => $i <= self::ASSIGNED_REP_COUNT && $reps->isNotEmpty() ? $reps->random()->id : null,
                'is_active' => true,
            ]);

            foreach (range(1, random_int(0, 2)) as $__) {
                $customer->contacts()->create([
                    'name' => fake()->name(),
                    'phone' => $this->srPhone(),
                ]);
            }

            foreach (range(1, random_int(0, 2)) as $__) {
                $customer->deliveryAddresses()->create([
                    'label' => fake()->randomElement(['Home', 'Office', 'Warehouse', 'Shop']),
                    'street_line1' => 'No. '.random_int(1, 300).', '.fake()->streetName(),
                    'city_id' => fake()->randomElement($cityIds),
                    'note' => null,
                ]);
            }
        }
    }
}
