<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // SQLite stores enums as CHECK constraints.
        // We need to recreate the table to remove/update the constraint.
        // This approach works for both SQLite and MySQL.

        $driver = DB::getDriverName();

        if ($driver === 'sqlite') {
            // For SQLite: recreate bulletins table without the enum CHECK constraint
            DB::statement('PRAGMA foreign_keys = OFF');

            DB::statement('
                CREATE TABLE bulletins_new (
                    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                    author_id INTEGER NOT NULL,
                    product_id INTEGER,
                    title VARCHAR(255) NOT NULL,
                    content LONGTEXT NOT NULL,
                    excerpt VARCHAR(500),
                    type VARCHAR(50) NOT NULL DEFAULT "announcement",
                    is_pinned TINYINT(1) NOT NULL DEFAULT 0,
                    is_published TINYINT(1) NOT NULL DEFAULT 0,
                    published_at DATETIME,
                    views_count INTEGER NOT NULL DEFAULT 0,
                    likes_count INTEGER NOT NULL DEFAULT 0,
                    created_at DATETIME,
                    updated_at DATETIME,
                    deleted_at DATETIME,
                    FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE CASCADE,
                    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE SET NULL
                )
            ');

            // Copy all existing data
            DB::statement('
                INSERT INTO bulletins_new
                SELECT id, author_id, product_id, title, content, excerpt, type,
                       is_pinned, is_published, published_at, views_count,
                       COALESCE(likes_count, 0),
                       created_at, updated_at, deleted_at
                FROM bulletins
            ');

            DB::statement('DROP TABLE bulletins');
            DB::statement('ALTER TABLE bulletins_new RENAME TO bulletins');
            DB::statement('PRAGMA foreign_keys = ON');

        } elseif ($driver === 'mysql' || $driver === 'mariadb') {
            DB::statement("
                ALTER TABLE bulletins
                MODIFY COLUMN type ENUM('alert','announcement','release','update','maintenance','warning')
                NOT NULL DEFAULT 'announcement'
            ");
        }
    }

    public function down(): void {}
};
