-- 2026-05-21: residential ↔ main-client auto-link.
--
-- Adds a nullable FK from `residential_clients` to the main `clients`
-- table. When the matching service finds a main-client record with the
-- same email / E.164 phone, the residential row is linked so reps can
-- see the cross-record relationship from either side without manual
-- de-duplication.
--
-- ON DELETE SET NULL keeps the residential record intact even if the
-- main client is hard-deleted (GDPR wipe etc.). Index supports
-- "what residential rows are linked to this main client" queries.

ALTER TABLE residential_clients
  ADD COLUMN linked_client_id text REFERENCES clients(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_residential_clients_linked_client
  ON residential_clients (linked_client_id)
  WHERE linked_client_id IS NOT NULL;
