CREATE TABLE IF NOT EXISTS business_scope_sync_run (
    run_id CHAR(32) NOT NULL PRIMARY KEY,
    source_system VARCHAR(32) NOT NULL,
    source_version VARCHAR(96) NOT NULL,
    status VARCHAR(24) NOT NULL,
    candidate_count INT UNSIGNED NOT NULL DEFAULT 0,
    accepted_count INT UNSIGNED NOT NULL DEFAULT 0,
    rejected_count INT UNSIGNED NOT NULL DEFAULT 0,
    source_checksum CHAR(64) NOT NULL,
    started_at DATETIME(3) NOT NULL,
    finished_at DATETIME(3) NOT NULL,
    error_message VARCHAR(512) NOT NULL DEFAULT '',
    INDEX idx_business_scope_run_finished (finished_at, status),
    INDEX idx_business_scope_run_version (source_version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS business_customer_vehicle_scope (
    source_version VARCHAR(96) NOT NULL,
    customer_id BIGINT NOT NULL,
    vin VARCHAR(64) NOT NULL,
    vehicle_id BIGINT NOT NULL,
    contract_id BIGINT NULL,
    contract_code VARCHAR(255) NOT NULL DEFAULT '',
    plate_number VARCHAR(64) NOT NULL DEFAULT '',
    project_name VARCHAR(255) NOT NULL DEFAULT '',
    operation_status VARCHAR(32) NOT NULL DEFAULT '',
    scope_start_at DATETIME(3) NOT NULL,
    source_updated_at DATETIME(3) NULL,
    published_at DATETIME(3) NOT NULL,
    PRIMARY KEY (source_version, customer_id, vin),
    UNIQUE KEY uk_business_scope_version_vehicle (source_version, vehicle_id),
    INDEX idx_business_scope_customer (customer_id, source_version, vin),
    INDEX idx_business_scope_vin (vin, source_version, customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS business_scope_rejection (
    run_id CHAR(32) NOT NULL,
    row_number INT UNSIGNED NOT NULL,
    vehicle_id BIGINT NULL,
    vin VARCHAR(64) NOT NULL DEFAULT '',
    customer_id BIGINT NULL,
    contract_id BIGINT NULL,
    reason_code VARCHAR(64) NOT NULL,
    created_at DATETIME(3) NOT NULL,
    PRIMARY KEY (run_id, row_number),
    INDEX idx_business_scope_rejection_reason (reason_code, created_at),
    CONSTRAINT fk_business_scope_rejection_run
        FOREIGN KEY (run_id) REFERENCES business_scope_sync_run(run_id)
        ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS business_scope_state (
    id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
    active_version VARCHAR(96) NULL,
    source_checksum CHAR(64) NULL,
    candidate_count INT UNSIGNED NOT NULL DEFAULT 0,
    accepted_count INT UNSIGNED NOT NULL DEFAULT 0,
    rejected_count INT UNSIGNED NOT NULL DEFAULT 0,
    generated_at DATETIME(3) NULL,
    published_at DATETIME(3) NULL,
    last_success_at DATETIME(3) NULL,
    CONSTRAINT chk_business_scope_singleton CHECK (id = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO business_scope_state(id) VALUES (1)
ON DUPLICATE KEY UPDATE id = VALUES(id);
