<?php

declare(strict_types=1);

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

/**
 * deals.subject_code range CHECK 1..89 — defensive parity с supplier_projects.subject_code (v8.26).
 *
 * Reviewer-finding (Plan 1 code-quality): supplier_projects.subject_code имеет CHECK 1..89,
 * deals.subject_code — только COMMENT. Malformed webhook tag → silent garbage в deals →
 * downstream report-by-region undercounts. NOT VALID + VALIDATE (squawk-safe), idempotent.
 */
return new class extends Migration
{
    public function up(): void
    {
        DB::statement(<<<'SQL'
            DO $$ BEGIN
              IF NOT EXISTS (
                SELECT 1 FROM pg_constraint WHERE conname = 'chk_deals_subject_code'
              ) THEN
                ALTER TABLE deals
                  ADD CONSTRAINT chk_deals_subject_code
                  CHECK (subject_code IS NULL OR (subject_code BETWEEN 1 AND 89)) NOT VALID;
              END IF;
            END $$;
        SQL);
        DB::statement('ALTER TABLE deals VALIDATE CONSTRAINT chk_deals_subject_code');
    }

    public function down(): void
    {
        DB::statement('ALTER TABLE deals DROP CONSTRAINT IF EXISTS chk_deals_subject_code');
    }
};
