<?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
    {
        if (! Schema::hasTable('findings')) {
            return;
        }

        if (! Schema::hasColumn('findings', 'first_seen_at')
            || ! Schema::hasColumn('findings', 'last_seen_at')
            || ! Schema::hasColumn('findings', 'times_seen')
        ) {
            return;
        }

        $driver = DB::getDriverName();

        DB::table('findings')
            ->whereNull('first_seen_at')
            ->update(['first_seen_at' => DB::raw('created_at')]);

        DB::table('findings')
            ->whereNull('last_seen_at')
            ->update(['last_seen_at' => DB::raw('COALESCE(first_seen_at, created_at)')]);

        DB::table('findings')
            ->whereNull('times_seen')
            ->orWhere('times_seen', '<', 1)
            ->update(['times_seen' => 1]);

        if ($driver === 'sqlite') {
            return;
        }

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE findings ALTER COLUMN first_seen_at SET NOT NULL');
            DB::statement('ALTER TABLE findings ALTER COLUMN last_seen_at SET NOT NULL');
            DB::statement('ALTER TABLE findings ALTER COLUMN times_seen SET NOT NULL');

            return;
        }

        if ($driver === 'mysql') {
            DB::statement('ALTER TABLE findings MODIFY first_seen_at TIMESTAMP NOT NULL');
            DB::statement('ALTER TABLE findings MODIFY last_seen_at TIMESTAMP NOT NULL');
            DB::statement('ALTER TABLE findings MODIFY times_seen INT NOT NULL');
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('findings')) {
            return;
        }

        $driver = DB::getDriverName();

        if ($driver === 'sqlite') {
            return;
        }

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE findings ALTER COLUMN first_seen_at DROP NOT NULL');
            DB::statement('ALTER TABLE findings ALTER COLUMN last_seen_at DROP NOT NULL');
            DB::statement('ALTER TABLE findings ALTER COLUMN times_seen DROP NOT NULL');

            return;
        }

        if ($driver === 'mysql') {
            DB::statement('ALTER TABLE findings MODIFY first_seen_at TIMESTAMP NULL');
            DB::statement('ALTER TABLE findings MODIFY last_seen_at TIMESTAMP NULL');
            DB::statement('ALTER TABLE findings MODIFY times_seen INT NULL');
        }
    }
};
