<?php

namespace Database\Seeders\Dummy;

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

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

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

            return;
        }

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

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

            return;
        }

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

        $clientNames = [
            '삼성전자', 'LG전자', 'SK하이닉스', '현대자동차', '네이버',
            '카카오', '쿠팡', '토스', '배달의민족', '당근마켓',
            '두산에너빌리티', 'CJ대한통운', '삼성SDS',
        ];

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

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

        $count = 0;
        $year = 2025;

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

            for ($i = 0; $i < $salesCount; $i++) {
                $day = (int) (($i + 1) * $daysInMonth / ($salesCount + 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]);
                }

                // 상태 결정: 1~10월 invoiced/confirmed, 11~12월 draft 포함
                if ($month <= 10) {
                    $status = rand(0, 1) ? 'invoiced' : 'confirmed';
                } elseif ($month == 11) {
                    $status = $i < 5 ? (rand(0, 1) ? 'invoiced' : 'confirmed') : 'draft';
                } else {
                    $status = $i < 1 ? 'confirmed' : 'draft';
                }

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

                Sale::create([
                    'tenant_id' => $tenantId,
                    'sale_number' => sprintf('SAL-%04d%02d-%04d', $year, $month, $i + 1),
                    'sale_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('   ✓ sales: '.$count.'건 생성');
    }
}
