<?php

namespace Database\Seeders\Dummy;

use App\Models\Orders\Client;
use App\Models\Tenants\Purchase;
use Database\Seeders\DummyDataSeeder;
use Illuminate\Database\Seeder;

class DummyPurchaseSeeder extends Seeder
{
    public function run(): void
    {
        $tenantId = DummyDataSeeder::TENANT_ID;
        $userId = DummyDataSeeder::USER_ID;

        // 기존 데이터 있으면 스킵
        $existing = Purchase::where('tenant_id', $tenantId)->count();
        if ($existing > 0) {
            $this->command->info('   ⚠ purchases: 이미 '.$existing.'건 존재 (스킵)');

            return;
        }

        // 거래처 매핑 (PURCHASE, BOTH만)
        $clients = Client::where('tenant_id', $tenantId)
            ->whereIn('client_type', ['PURCHASE', 'BOTH'])
            ->get();

        if ($clients->isEmpty()) {
            $this->command->warn('   ⚠ purchases: 매입 거래처 없음 (스킵)');

            return;
        }

        $clientsByName = $clients->keyBy('name');
        $clientIds = $clients->pluck('id')->toArray();

        $clientNames = [
            '한화솔루션', '포스코', '롯데케미칼', 'GS칼텍스', '대한항공',
            '현대제철', 'SK이노베이션', 'CJ대한통운', '두산에너빌리티',
        ];

        $amounts = [
            'small' => [1000000, 5000000],
            'medium' => [5000000, 30000000],
            'large' => [30000000, 80000000],
        ];

        // 월별 건수: 1~10월 5~6건, 11월 7건, 12월 6건 = 70건
        $monthlyCount = [5, 5, 6, 5, 6, 6, 6, 6, 6, 6, 7, 6];

        $count = 0;
        $year = 2025;

        for ($month = 1; $month <= 12; $month++) {
            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            $purchaseCount = $monthlyCount[$month - 1];

            for ($i = 0; $i < $purchaseCount; $i++) {
                $day = (int) (($i + 1) * $daysInMonth / ($purchaseCount + 1));
                $day = max(1, min($day, $daysInMonth));

                $clientName = $clientNames[($count) % count($clientNames)];
                $client = $clientsByName->get($clientName);

                // 이름 매칭 실패 시 기존 클라이언트 중 랜덤 선택
                if (! $client) {
                    $clientId = $clientIds[array_rand($clientIds)];
                    $client = $clients->firstWhere('id', $clientId);
                    $clientName = $client->name;
                }

                $rand = rand(1, 100);
                if ($rand <= 30) {
                    $supply = rand($amounts['small'][0], $amounts['small'][1]);
                } elseif ($rand <= 80) {
                    $supply = rand($amounts['medium'][0], $amounts['medium'][1]);
                } else {
                    $supply = rand($amounts['large'][0], $amounts['large'][1]);
                }

                // 상태 결정
                if ($month <= 10) {
                    $status = 'confirmed';
                } elseif ($month == 11) {
                    $status = $i < 4 ? 'confirmed' : 'draft';
                } else {
                    $status = $i < 1 ? 'confirmed' : 'draft';
                }

                $tax = round($supply * 0.1);
                $total = $supply + $tax;

                Purchase::create([
                    'tenant_id' => $tenantId,
                    'purchase_number' => sprintf('PUR-%04d%02d-%04d', $year, $month, $i + 1),
                    'purchase_date' => sprintf('%04d-%02d-%02d', $year, $month, $day),
                    'client_id' => $client->id,
                    'supply_amount' => $supply,
                    'tax_amount' => $tax,
                    'total_amount' => $total,
                    'description' => $clientName.' 매입',
                    'status' => $status,
                    'created_by' => $userId,
                ]);

                $count++;
            }
        }

        $this->command->info('   ✓ purchases: '.$count.'건 생성');
    }
}
