-- CL3.6a: Instance health + domains visibility

alter table public.plesk_instances
  add column if not exists last_sync_at timestamptz,
  add column if not exists last_sync_status text,
  add column if not exists last_sync_error text,
  add column if not exists last_sync_subscriptions integer not null default 0,
  add column if not exists last_sync_domains integer not null default 0;

update public.plesk_instances
set
  last_sync_subscriptions = coalesce(last_sync_subscriptions, 0),
  last_sync_domains = coalesce(last_sync_domains, 0);

alter table public.plesk_instances
  alter column last_sync_subscriptions set default 0,
  alter column last_sync_domains set default 0,
  alter column last_sync_subscriptions set not null,
  alter column last_sync_domains set not null;

alter table public.plesk_instances
  drop constraint if exists plesk_instances_status_check;

alter table public.plesk_instances
  add constraint plesk_instances_status_check
  check (status in ('connected', 'error', 'disabled', 'syncing'));

alter table public.plesk_domains
  add column if not exists hosting_type text,
  add column if not exists source_created_at timestamptz,
  add column if not exists aliases_count integer,
  add column if not exists updated_at timestamptz not null default now();

drop trigger if exists trg_plesk_domains_updated_at on public.plesk_domains;
create trigger trg_plesk_domains_updated_at
before update on public.plesk_domains
for each row execute function public.set_updated_at();
