-- 0086_tenancies_self_fks.sql
-- Add self-FKs for renewals + transfers per docs/tenancies-design.md
-- §"Data model > Rename migration". `previous_tenancy_id` chains a new
-- row to the row it succeeds (fixed-term + seasonal renewals mint a new
-- row; permanent renewals mutate in place). `transferred_from_tenancy_id`
-- chains a new row to the predecessor when an active tenancy is
-- handed over to a different client/yacht.

ALTER TABLE berth_tenancies
  ADD COLUMN IF NOT EXISTS previous_tenancy_id text REFERENCES berth_tenancies(id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS transferred_from_tenancy_id text REFERENCES berth_tenancies(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_bt_previous ON berth_tenancies(previous_tenancy_id) WHERE previous_tenancy_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_bt_transferred_from ON berth_tenancies(transferred_from_tenancy_id) WHERE transferred_from_tenancy_id IS NOT NULL;
