<?php

namespace Database\Seeders\Dummy;

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

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

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

            return;
        }

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

        // 은행계좌
        $primaryBankId = BankAccount::where('tenant_id', $tenantId)
            ->where('is_primary', true)
            ->value('id');

        // 결제수단 분포
        $methods = array_merge(
            array_fill(0, 14, 'transfer'),
            array_fill(0, 3, 'card'),
            array_fill(0, 2, 'cash'),
            array_fill(0, 1, 'check')
        );

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

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

        $count = 0;
        $year = 2025;

        for ($month = 1; $month <= 12; $month++) {
            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

            for ($i = 0; $i < 5; $i++) {
                $day = rand(1, $daysInMonth);
                $clientName = $clientNames[($month * 5 + $i) % count($clientNames)];
                $client = $clients->get($clientName);

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

                Withdrawal::create([
                    'tenant_id' => $tenantId,
                    'withdrawal_date' => sprintf('%04d-%02d-%02d', $year, $month, $day),
                    'client_id' => $client?->id,
                    'client_name' => $client ? null : $clientName,
                    'bank_account_id' => $primaryBankId,
                    'amount' => $amount,
                    'payment_method' => $methods[array_rand($methods)],
                    'description' => $clientName.' 지급',
                    'created_by' => $userId,
                ]);

                $count++;
            }
        }

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