CREATE TABLE IF NOT EXISTS carteras (
  id                 uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  supervisor_user_id uuid NOT NULL,
  nombre             text NOT NULL,
  descripcion        text,
  created_at         timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_carteras_supervisor ON carteras(supervisor_user_id);

CREATE TABLE IF NOT EXISTS cartera_entidades (
  cartera_id uuid NOT NULL REFERENCES carteras(id) ON DELETE CASCADE,
  entidad_id uuid NOT NULL REFERENCES entidades_gestionadas(id) ON DELETE CASCADE,
  added_at   timestamptz DEFAULT now(),
  PRIMARY KEY (cartera_id, entidad_id)
);

CREATE TABLE IF NOT EXISTS cartera_auxiliares (
  cartera_id       uuid NOT NULL REFERENCES carteras(id) ON DELETE CASCADE,
  auxiliar_user_id uuid NOT NULL,
  added_at         timestamptz DEFAULT now(),
  PRIMARY KEY (cartera_id, auxiliar_user_id)
);

INSERT INTO tenant_migrations (scope, version, name)
VALUES ('core', 8, '008_carteras')
ON CONFLICT (scope, version) DO NOTHING;
