CREATE TABLE IF NOT EXISTS tickets (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    source VARCHAR(64) NOT NULL,
    external_id VARCHAR(255) NOT NULL,
    title VARCHAR(512) NOT NULL,
    status VARCHAR(64) NOT NULL,
    opened_at TIMESTAMP NULL,
    closed_at TIMESTAMP NULL,
    url VARCHAR(512) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_tickets_source_external (source, external_id)
);

CREATE TABLE IF NOT EXISTS ticket_links (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    ticket_id BIGINT NOT NULL,
    asset_id BIGINT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_ticket_links_ticket
        FOREIGN KEY (ticket_id) REFERENCES tickets(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT fk_ticket_links_asset
        FOREIGN KEY (asset_id) REFERENCES assets(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    UNIQUE KEY uniq_ticket_links_ticket_asset (ticket_id, asset_id)
);

CREATE INDEX idx_ticket_links_asset ON ticket_links(asset_id, ticket_id);
