<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

return new class extends Migration
{
    public function up(): void
    {
        // Log rows with both period_month AND period_quarter set
        $ambiguousRows = DB::table('folders')
            ->where('type', 'vat')
            ->whereNotNull('period_month')
            ->whereNotNull('period_quarter')
            ->pluck('id');

        if ($ambiguousRows->isNotEmpty()) {
            Log::warning('VAT folders with both period_month AND period_quarter set (migrated as vat_monthly, quarter nulled): '.$ambiguousRows->implode(', '));
        }

        // Monthly: has month, no quarter
        DB::table('folders')
            ->where('type', 'vat')
            ->whereNotNull('period_month')
            ->whereNull('period_quarter')
            ->update(['type' => 'vat_monthly']);

        // Quarterly: has quarter, no month
        DB::table('folders')
            ->where('type', 'vat')
            ->whereNotNull('period_quarter')
            ->whereNull('period_month')
            ->update(['type' => 'vat_quarterly']);

        // Both set: treat as monthly, null quarter
        DB::table('folders')
            ->where('type', 'vat')
            ->whereNotNull('period_month')
            ->whereNotNull('period_quarter')
            ->update(['type' => 'vat_monthly', 'period_quarter' => null]);

        // Neither set: fallback to monthly
        DB::table('folders')
            ->where('type', 'vat')
            ->whereNull('period_month')
            ->whereNull('period_quarter')
            ->update(['type' => 'vat_monthly']);
    }

    public function down(): void
    {
        DB::table('folders')
            ->whereIn('type', ['vat_monthly', 'vat_quarterly'])
            ->update(['type' => 'vat']);
    }
};
