<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('ticket_department_mailboxes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('ticket_department_id')->constrained()->onDelete('cascade');
            $table->string('label', 100)->nullable();
            $table->string('protocol', 10)->default('pop3');
            $table->string('hostname', 255)->nullable();
            $table->integer('port')->default(995);
            $table->string('email', 255)->nullable();
            $table->string('password', 255)->nullable();
            $table->boolean('ssl')->default(true);
            $table->boolean('enabled')->default(true);
            $table->string('auth_type', 20)->default('password');
            $table->text('footer_strip')->nullable();
            $table->integer('poll_interval')->default(5);
            $table->string('post_action', 20)->default('mark_read');
            $table->string('move_folder', 255)->nullable();
            $table->timestamp('last_checked_at')->nullable();
            $table->integer('last_message_count')->nullable();
            $table->timestamps();

            $table->index('ticket_department_id');
        });

        // Migrate existing mailbox data from ticket_departments to new table
        $departments = DB::table('ticket_departments')
            ->whereNotNull('mail_hostname')
            ->where('mail_hostname', '!=', '')
            ->get();

        foreach ($departments as $dept) {
            DB::table('ticket_department_mailboxes')->insert([
                'ticket_department_id' => $dept->id,
                'label' => 'Primary',
                'protocol' => $dept->mail_protocol ?? 'pop3',
                'hostname' => $dept->mail_hostname,
                'port' => $dept->mail_port ?? 995,
                'email' => $dept->mail_email,
                'password' => $dept->mail_password,
                'ssl' => $dept->mail_ssl ?? true,
                'enabled' => $dept->mail_import_enabled ?? false,
                'auth_type' => $dept->mail_auth_type ?? 'password',
                'footer_strip' => $dept->mail_footer_strip,
                'poll_interval' => $dept->mail_poll_interval ?? 5,
                'post_action' => $dept->mail_post_action ?? 'mark_read',
                'move_folder' => $dept->mail_move_folder,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

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