<?php

namespace Database\Seeders\Dummy;

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

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

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

            return;
        }

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

        // 은행계좌 (대표계좌 우선)
        $bankAccounts = BankAccount::where('tenant_id', $tenantId)
            ->where('status', 'active')
            ->orderByDesc('is_primary')
            ->get();

        $primaryBankId = $bankAccounts->first()?->id;

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

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

        // 금액 범위
        $amounts = [
            'small' => [1000000, 5000000],     // 30%
            'medium' => [5000000, 30000000],    // 50%
            'large' => [30000000, 100000000],  // 20%
        ];

        $count = 0;
        $year = 2025;

        // 월별 5건씩, 총 60건
        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]);
                }

                Deposit::create([
                    'tenant_id' => $tenantId,
                    'deposit_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('   ✓ deposits: '.$count.'건 생성');
    }
}
