PRAGMA foreign_keys = OFF;

CREATE TABLE service_bindings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    domain_id INTEGER NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
    service_id INTEGER NOT NULL REFERENCES services(id) ON DELETE CASCADE,
    hostname TEXT NOT NULL DEFAULT '@',
    dns_record_id INTEGER REFERENCES dns_records(id) ON DELETE SET NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(domain_id, service_id, hostname)
);

CREATE INDEX idx_service_bindings_domain_id ON service_bindings(domain_id);
CREATE INDEX idx_service_bindings_service_id ON service_bindings(service_id);

INSERT INTO service_bindings (domain_id, service_id, hostname, created_at, updated_at)
SELECT domain_id, service_id, '@', datetime('now'), datetime('now')
FROM domain_services;

DROP TABLE domain_services;

PRAGMA foreign_keys = ON;
