<?php

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

/**
 * E-posta Filtreleri (sieve script benzeri).
 *
 * Sender/subject/body match → fail/discard/forward/save-to-folder.
 * Üretimde Dovecot Sieve script'i veya Postfix transport tablosu üretir.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('email_filters', function (Blueprint $table) {
            $table->id();

            $table->foreignId('email_account_id')
                ->constrained('email_accounts')
                ->cascadeOnDelete();

            $table->string('name', 100);
            $table->unsignedInteger('priority')->default(10)
                ->comment('Düşük = önce çalışır');

            $table->enum('match_field', ['from', 'to', 'subject', 'body', 'any_header'])
                ->default('subject');
            $table->enum('match_operator', ['contains', 'equals', 'starts_with', 'ends_with', 'regex', 'not_contains'])
                ->default('contains');
            $table->string('match_value', 255);
            $table->boolean('match_case_sensitive')->default(false);

            $table->enum('action', ['discard', 'fail', 'redirect', 'save_to_folder', 'forward', 'reject'])
                ->default('save_to_folder');
            $table->string('action_value', 255)->nullable()
                ->comment('Folder name, redirect address, reject message vd.');

            $table->boolean('stop_on_match')->default(true)
                ->comment('Eşleşince sonraki filtreleri çalıştırma');
            $table->boolean('is_active')->default(true);

            $table->timestamps();
            $table->softDeletes();

            $table->index(['email_account_id', 'priority']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('email_filters');
    }
};
