ALTER TABLE service_bindings ADD COLUMN cert_monitoring TEXT NOT NULL DEFAULT 'auto'
  CHECK (cert_monitoring IN ('auto', 'required', 'skipped'));

ALTER TABLE certificates ADD COLUMN service_id INTEGER REFERENCES services(id) ON DELETE SET NULL;

UPDATE service_bindings
SET cert_monitoring = COALESCE(
  (
    SELECT d.cert_monitoring FROM domains d
    WHERE d.id = service_bindings.domain_id
  ),
  'auto'
)
WHERE hostname = '@';

UPDATE service_bindings
SET cert_monitoring = COALESCE(
  (
    SELECT s.cert_monitoring FROM subdomains s
    WHERE s.domain_id = service_bindings.domain_id
      AND s.name = service_bindings.hostname
  ),
  'auto'
)
WHERE hostname != '@';

UPDATE certificates
SET service_id = (
  SELECT sb.service_id
  FROM service_bindings sb
  JOIN domains d ON d.id = sb.domain_id
  WHERE CASE
    WHEN sb.hostname = '@' THEN d.zone_name
    ELSE sb.hostname || '.' || d.zone_name
  END = certificates.hostname
  LIMIT 1
);
