<?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('audit_logs')) {
            return;
        }

        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE audit_logs ADD CONSTRAINT audit_logs_tenant_workspace_scope_check CHECK (managed_environment_id IS NULL OR workspace_id IS NOT NULL)');

            return;
        }

        if ($driver === 'mysql') {
            DB::statement('ALTER TABLE audit_logs ADD CONSTRAINT audit_logs_tenant_workspace_scope_check CHECK (managed_environment_id IS NULL OR workspace_id IS NOT NULL)');
        }
    }

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

        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE audit_logs DROP CONSTRAINT IF EXISTS audit_logs_tenant_workspace_scope_check');

            return;
        }

        if ($driver === 'mysql') {
            DB::statement('ALTER TABLE audit_logs DROP CHECK audit_logs_tenant_workspace_scope_check');
        }
    }
};
