<?php

namespace Database\Seeders;

use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DimDateSeeder extends Seeder
{
    public function run(): void
    {
        $start = Carbon::create(2020, 1, 1);
        $end = Carbon::create(2030, 12, 31);
        $period = CarbonPeriod::create($start, $end);

        $holidays = $this->getKoreanHolidays();

        $batch = [];
        $batchSize = 500;

        foreach ($period as $date) {
            $dateStr = $date->format('Y-m-d');
            $holiday = $holidays[$dateStr] ?? null;

            $batch[] = [
                'date_key' => $dateStr,
                'year' => $date->year,
                'quarter' => $date->quarter,
                'month' => $date->month,
                'week' => (int) $date->isoWeek(),
                'day_of_week' => $date->dayOfWeekIso,
                'day_of_month' => $date->day,
                'is_weekend' => $date->isWeekend(),
                'is_holiday' => $holiday !== null,
                'holiday_name' => $holiday,
                'fiscal_year' => $date->year,
                'fiscal_quarter' => $date->quarter,
            ];

            if (count($batch) >= $batchSize) {
                DB::connection('sam_stat')->table('dim_date')->insert($batch);
                $batch = [];
            }
        }

        if (! empty($batch)) {
            DB::connection('sam_stat')->table('dim_date')->insert($batch);
        }

        $totalCount = DB::connection('sam_stat')->table('dim_date')->count();
        $this->command->info("dim_date 시딩 완료: {$totalCount}건 (2020-01-01 ~ 2030-12-31)");
    }

    /**
     * 한국 공휴일 목록 (고정 공휴일만, 음력 공휴일은 수동 추가 필요)
     */
    private function getKoreanHolidays(): array
    {
        $holidays = [];

        for ($year = 2020; $year <= 2030; $year++) {
            // 고정 공휴일
            $fixed = [
                "{$year}-01-01" => '신정',
                "{$year}-03-01" => '삼일절',
                "{$year}-05-05" => '어린이날',
                "{$year}-06-06" => '현충일',
                "{$year}-08-15" => '광복절',
                "{$year}-10-03" => '개천절',
                "{$year}-10-09" => '한글날',
                "{$year}-12-25" => '크리스마스',
            ];

            $holidays = array_merge($holidays, $fixed);
        }

        return $holidays;
    }
}
