-- 0085_rename_reservations_to_tenancies.sql
-- Rename berth_reservations → berth_tenancies (table + indexes + FK constraints +
-- documents.reservation_id column) and migrate jsonb permission maps (rename
-- the `reservations` resource key → `tenancies`, collapse the create/activate
-- actions into a single `manage`). See docs/tenancies-design.md.
--
-- The data is preserved verbatim; this is a pure rename at the storage
-- layer. Permission shape change: { view, create, activate, cancel }
-- collapses to { view, manage, cancel } (manage = old create OR activate).

-- 1. Rename the table.
ALTER TABLE berth_reservations RENAME TO berth_tenancies;

-- 2. Rename indexes (idx_br_* / idx_brr_* → idx_bt_*).
ALTER INDEX idx_br_berth RENAME TO idx_bt_berth;
ALTER INDEX idx_br_client RENAME TO idx_bt_client;
ALTER INDEX idx_br_yacht RENAME TO idx_bt_yacht;
ALTER INDEX idx_br_port RENAME TO idx_bt_port;
ALTER INDEX idx_brr_interest RENAME TO idx_bt_interest;
ALTER INDEX idx_brr_contract_file RENAME TO idx_bt_contract_file;
ALTER INDEX idx_br_active RENAME TO idx_bt_active;

-- 3. Rename FK constraints so Drizzle-derived names match the new table.
--    Wrapped in DO-blocks so dev DBs that pre-date 0042 (and therefore
--    are missing some FKs) don't abort the migration.
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_berth_id_berths_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_berth_id_berths_id_fk TO berth_tenancies_berth_id_berths_id_fk;
  END IF;
END $$;
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_port_id_ports_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_port_id_ports_id_fk TO berth_tenancies_port_id_ports_id_fk;
  END IF;
END $$;
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_client_id_clients_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_client_id_clients_id_fk TO berth_tenancies_client_id_clients_id_fk;
  END IF;
END $$;
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_yacht_id_yachts_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_yacht_id_yachts_id_fk TO berth_tenancies_yacht_id_yachts_id_fk;
  END IF;
END $$;
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_interest_id_interests_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_interest_id_interests_id_fk TO berth_tenancies_interest_id_interests_id_fk;
  END IF;
END $$;
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_contract_file_id_files_id_fk') THEN
    ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_contract_file_id_files_id_fk TO berth_tenancies_contract_file_id_files_id_fk;
  END IF;
END $$;

-- 4. Rename the FK column on documents from reservation_id → tenancy_id.
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='documents' AND column_name='reservation_id') THEN
    ALTER TABLE documents RENAME COLUMN reservation_id TO tenancy_id;
  END IF;
END $$;

DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_indexes WHERE tablename='documents' AND indexname='idx_docs_reservation') THEN
    ALTER INDEX idx_docs_reservation RENAME TO idx_docs_tenancy;
  END IF;
END $$;

DO $$ BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conrelid = 'documents'::regclass
      AND conname = 'documents_reservation_id_berth_reservations_id_fk'
  ) THEN
    ALTER TABLE documents RENAME CONSTRAINT documents_reservation_id_berth_reservations_id_fk TO documents_tenancy_id_berth_tenancies_id_fk;
  END IF;
END $$;

-- 5. Migrate jsonb permission maps: rename the resource key + collapse actions.
UPDATE roles
SET permissions = (
  (permissions - 'reservations') ||
  jsonb_build_object(
    'tenancies',
    jsonb_build_object(
      'view',   COALESCE((permissions -> 'reservations' ->> 'view')::boolean, false),
      'manage', (COALESCE((permissions -> 'reservations' ->> 'create')::boolean, false)
              OR COALESCE((permissions -> 'reservations' ->> 'activate')::boolean, false)),
      'cancel', COALESCE((permissions -> 'reservations' ->> 'cancel')::boolean, false)
    )
  )
)
WHERE permissions ? 'reservations';

UPDATE port_role_overrides
SET permission_overrides = (
  (permission_overrides - 'reservations') ||
  jsonb_build_object(
    'tenancies',
    jsonb_build_object(
      'view',   COALESCE((permission_overrides -> 'reservations' ->> 'view')::boolean, false),
      'manage', (COALESCE((permission_overrides -> 'reservations' ->> 'create')::boolean, false)
              OR COALESCE((permission_overrides -> 'reservations' ->> 'activate')::boolean, false)),
      'cancel', COALESCE((permission_overrides -> 'reservations' ->> 'cancel')::boolean, false)
    )
  )
)
WHERE permission_overrides ? 'reservations';

UPDATE user_permission_overrides
SET permission_overrides = (
  (permission_overrides - 'reservations') ||
  jsonb_build_object(
    'tenancies',
    jsonb_build_object(
      'view',   COALESCE((permission_overrides -> 'reservations' ->> 'view')::boolean, false),
      'manage', (COALESCE((permission_overrides -> 'reservations' ->> 'create')::boolean, false)
              OR COALESCE((permission_overrides -> 'reservations' ->> 'activate')::boolean, false)),
      'cancel', COALESCE((permission_overrides -> 'reservations' ->> 'cancel')::boolean, false)
    )
  )
)
WHERE permission_overrides ? 'reservations';

-- 6. Migrate historical audit-log entity_type strings so the dashboard
--    activity feed groups old + new events under the same label.
UPDATE audit_logs SET entity_type = 'berth_tenancy'
WHERE entity_type = 'berth_reservation';
