<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        $departments = config('tickets.departments', ['billing', 'technical', 'sales', 'general']);

        foreach ($departments as $index => $department) {
            DB::table('departments')->insertOrIgnore([
                'name' => Str::title($department),
                'slug' => Str::slug($department),
                'sort_order' => $index,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // Update existing support_tickets to set department_id based on department string
        $deptRows = DB::table('departments')->get();

        foreach ($deptRows as $dept) {
            DB::table('support_tickets')
                ->where('department', $dept->slug)
                ->whereNull('department_id')
                ->update(['department_id' => $dept->id]);
        }
    }

    public function down(): void
    {
        // Keep old department column data intact; just clear the department_id
        DB::table('support_tickets')->update(['department_id' => null]);

        $departments = config('tickets.departments', ['billing', 'technical', 'sales', 'general']);

        foreach ($departments as $department) {
            DB::table('departments')->where('slug', Str::slug($department))->delete();
        }
    }
};
