<?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::create('recurring_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('source_transaction_id')->nullable()->constrained('transactions')->onDelete('set null');
            
            // Identificação
            $table->string('name'); // "Aluguel Apartamento"
            $table->text('description')->nullable();
            
            // Frequência
            $table->enum('frequency', [
                'daily',      // Diária
                'weekly',     // Semanal
                'biweekly',   // Quinzenal
                'monthly',    // Mensal
                'bimonthly',  // Bimestral
                'quarterly',  // Trimestral
                'semiannual', // Semestral
                'annual'      // Anual
            ]);
            $table->unsignedTinyInteger('frequency_interval')->default(1); // A cada X períodos
            
            // Configuração de dia
            $table->unsignedTinyInteger('day_of_month')->nullable(); // 1-31 para mensal+
            $table->unsignedTinyInteger('day_of_week')->nullable();  // 0-6 para semanal (0=domingo)
            
            // Período de vigência
            $table->date('start_date');
            $table->date('end_date')->nullable(); // null = infinito
            $table->unsignedInteger('max_occurrences')->nullable(); // null = infinito
            
            // Dados do template (herdados nas instâncias)
            $table->foreignId('account_id')->constrained()->onDelete('cascade');
            $table->foreignId('category_id')->nullable()->constrained()->onDelete('set null');
            $table->foreignId('cost_center_id')->nullable()->constrained()->onDelete('set null');
            $table->enum('type', ['credit', 'debit']);
            $table->decimal('planned_amount', 15, 2);
            $table->string('transaction_description', 255); // Descrição que vai na transação
            $table->text('notes')->nullable();
            
            // Controle
            $table->boolean('is_active')->default(true);
            $table->date('last_generated_date')->nullable();
            $table->unsignedInteger('occurrences_generated')->default(0);
            
            $table->timestamps();
            $table->softDeletes();
            
            // Índices
            $table->index(['user_id', 'is_active']);
            $table->index(['user_id', 'frequency']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('recurring_templates');
    }
};
