-- Down migration for t-paliad-139 (055_hierarchy_aggregation).
--
-- Reverses the schema additions in lockstep with the up migration:
--   1. Restore can_see_project to the migration-023 body (drop derivation
--      branch).
--   2. Drop paliad.approval_role_from_unit_role helper.
--   3. Drop paliad.project_partner_units (cascades the policies + index).
--   4. Drop paliad.partner_unit_members.unit_role.
--
-- If any project has project_partner_units rows with derive_grants_authority=true
-- AND any approval_request was ever signed using a derived_peer decision_kind
-- (t-paliad-139 Phase 3), the down does NOT roll those back — the audit rows
-- stay valid; only the schema is reverted. Down is intentionally lossy on
-- in-flight derivation state.

-- Restore the migration-054 decision_kind CHECK (without 'derived_peer').
-- Any existing rows with decision_kind='derived_peer' would fail the
-- restored CHECK; the down deliberately doesn't update them — operators
-- must reconcile before applying the down migration.
ALTER TABLE paliad.approval_requests DROP CONSTRAINT IF EXISTS approval_requests_decision_kind_check;
ALTER TABLE paliad.approval_requests ADD CONSTRAINT approval_requests_decision_kind_check
    CHECK (decision_kind IS NULL OR decision_kind IN ('peer', 'admin_override'));

-- 1. Restore migration-023 can_see_project body (no derivation branch).
CREATE OR REPLACE FUNCTION paliad.can_see_project(_project_id uuid)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = paliad, public
AS $$
    SELECT EXISTS (
        SELECT 1 FROM paliad.users u
         WHERE u.id = auth.uid() AND u.global_role = 'global_admin'
    )
    OR EXISTS (
        SELECT 1
          FROM paliad.projects      target
          JOIN paliad.project_teams pt
            ON pt.user_id = auth.uid()
           AND pt.project_id = ANY(string_to_array(target.path, '.')::uuid[])
         WHERE target.id = _project_id
    );
$$;

-- 2. Drop the unit_role → project_role mapping helper.
DROP FUNCTION IF EXISTS paliad.approval_role_from_unit_role(text);

-- 3. Drop the project↔unit junction (CASCADE clears policies + index).
DROP TABLE IF EXISTS paliad.project_partner_units;

-- 4. Drop the unit_role column.
ALTER TABLE paliad.partner_unit_members DROP COLUMN IF EXISTS unit_role;
