<?php

namespace Database\Seeders\Dummy;

use App\Models\BadDebts\BadDebt;
use App\Models\Orders\Client;
use Database\Seeders\DummyDataSeeder;
use Illuminate\Database\Seeder;

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

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

            return;
        }

        // SALES 또는 BOTH 타입의 거래처 조회
        $clients = Client::where('tenant_id', $tenantId)
            ->whereIn('client_type', ['SALES', 'BOTH'])
            ->get();

        if ($clients->isEmpty()) {
            $this->command->warn('   ⚠ clients 데이터가 없습니다. DummyClientSeeder를 먼저 실행하세요.');

            return;
        }

        // 상태별 분포
        $statuses = [
            'collecting' => 6,  // 추심중
            'legal_action' => 4,  // 법적조치
            'recovered' => 5,  // 회수완료
            'bad_debt' => 3,  // 대손처리
        ];

        // 금액 범위 (채권 금액)
        $amounts = [
            'small' => [500000, 3000000],      // 50만~300만
            'medium' => [3000000, 15000000],    // 300만~1500만
            'large' => [15000000, 50000000],   // 1500만~5000만
        ];

        $count = 0;
        $year = 2025;
        $clientIndex = 0;

        foreach ($statuses as $status => $qty) {
            for ($i = 0; $i < $qty; $i++) {
                $client = $clients[$clientIndex % $clients->count()];
                $clientIndex++;

                // 발생월 (1~10월 사이 랜덤)
                $month = rand(1, 10);
                $day = rand(1, 28);
                $occurredAt = sprintf('%04d-%02d-%02d', $year, $month, $day);

                // 연체일수 계산 (발생일로부터 현재까지)
                $occurredDate = new \DateTime($occurredAt);
                $now = new \DateTime('2025-12-23');
                $overdueDays = $occurredDate->diff($now)->days;

                // 금액 결정 (분포에 따라)
                $rand = rand(1, 100);
                if ($rand <= 40) {
                    $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]);
                }

                // 종료일 (회수완료/대손처리인 경우만)
                $closedAt = null;
                if (in_array($status, ['recovered', 'bad_debt'])) {
                    $closedMonth = rand($month + 1, 12);
                    $closedDay = rand(1, 28);
                    $closedAt = sprintf('%04d-%02d-%02d', $year, $closedMonth, $closedDay);
                }

                BadDebt::create([
                    'tenant_id' => $tenantId,
                    'client_id' => $client->id,
                    'debt_amount' => $amount,
                    'status' => $status,
                    'overdue_days' => $overdueDays,
                    'assigned_user_id' => $userId,
                    'occurred_at' => $occurredAt,
                    'closed_at' => $closedAt,
                    'is_active' => true,
                    'options' => null,
                    'created_by' => $userId,
                ]);

                $count++;
            }
        }

        $this->command->info('   ✓ bad_debts: '.$count.'건 생성');
        $this->command->info('     - collecting: 6건, legal_action: 4건, recovered: 5건, bad_debt: 3건');
    }
}
