-- Subcarteras: a cartera can be a child of another cartera.
-- Top-level carteras belong to a supervisor (or owner).
-- Subcarteras belong to an auxiliar within a parent cartera.

ALTER TABLE carteras
  ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES carteras(id) ON DELETE CASCADE;

ALTER TABLE carteras
  ADD COLUMN IF NOT EXISTS auxiliar_user_id uuid;

-- Allow supervisor_user_id to be NULL for subcarteras (inherited from parent)
ALTER TABLE carteras
  ALTER COLUMN supervisor_user_id DROP NOT NULL;

CREATE INDEX IF NOT EXISTS ix_carteras_parent ON carteras(parent_id);
CREATE INDEX IF NOT EXISTS ix_carteras_auxiliar ON carteras(auxiliar_user_id);

-- Track which supervisor an auxiliar reports to (1:1 per auxiliar)
CREATE TABLE IF NOT EXISTS auxiliar_supervisores (
  auxiliar_user_id   uuid NOT NULL PRIMARY KEY,
  supervisor_user_id uuid NOT NULL,
  created_at         timestamptz DEFAULT now()
);
