-- Personal report document v2 persistence metadata.
--
-- Existing v1 rows remain readable. New report creation persists an explicit
-- product depth and the current report_document.v2 schema version.

begin;

-- The hosted Supabase stream added named Skill identity in the preceding
-- immutable-registry migration. The self-hosted/local stream does not carry
-- that historical migration, so repeat the forward-compatible columns here.
-- `if not exists` keeps the two migration streams byte-identical and safe.
alter table public.personal_reports
  add column if not exists skill_name text
    check (
      skill_name is null
      or skill_name ~ '^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$'
    ),
  add column if not exists skill_version text
    check (
      skill_version is null
      or (
        length(skill_version) between 5 and 80
        and skill_version ~ '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'
      )
    );

alter table public.personal_reports
  add column if not exists depth text not null default 'standard';

alter table public.personal_reports
  drop constraint if exists personal_reports_depth_check;
alter table public.personal_reports
  add constraint personal_reports_depth_check
  check (depth in ('concise', 'standard', 'deep', 'research'));

alter table public.personal_reports
  drop constraint if exists personal_reports_schema_version_check;
alter table public.personal_reports
  add constraint personal_reports_schema_version_check
  check (schema_version in ('report_document.v1', 'report_document.v2'));

commit;
