<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('budgets', function (Blueprint $table) {
            // Adicionar subcategory_id
            $table->foreignId('subcategory_id')->nullable()->after('category_id')->constrained('categories')->onDelete('cascade');
            
            // Remover unique constraint antiga
            $table->dropUnique('unique_budget_category_period');
            
            // Nova unique constraint incluindo subcategoria
            $table->unique(['user_id', 'category_id', 'subcategory_id', 'year', 'month'], 'unique_budget_period');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('budgets', function (Blueprint $table) {
            // Remover nova constraint
            $table->dropUnique('unique_budget_period');
            
            // Restaurar constraint antiga
            $table->unique(['user_id', 'category_id', 'year', 'month'], 'unique_budget_category_period');
            
            // Remover coluna
            $table->dropForeign(['subcategory_id']);
            $table->dropColumn('subcategory_id');
        });
    }
};
