-- Reverse of 111_project_admin_and_select.up.sql.
--
-- Drops effective_project_admin, restores the original RLS policies,
-- and shrinks the responsibility CHECK back to four values. Any rows
-- still carrying responsibility='admin' would violate the restored
-- CHECK; the down-migration backfills them to 'lead' (the closest
-- existing role) before re-adding the constraint.

-- ============================================================================
-- 1. Backfill any responsibility='admin' rows to 'lead'.
-- ============================================================================

UPDATE paliad.project_teams
   SET responsibility = 'lead'
 WHERE responsibility = 'admin';

-- ============================================================================
-- 2. Restore the original CHECK (lead/member/observer/external).
-- ============================================================================

ALTER TABLE paliad.project_teams
    DROP CONSTRAINT IF EXISTS project_teams_responsibility_check;

ALTER TABLE paliad.project_teams
    ADD CONSTRAINT project_teams_responsibility_check
    CHECK (responsibility IN ('lead', 'member', 'observer', 'external'));

-- ============================================================================
-- 3. Restore the pre-110 RLS policies.
-- ============================================================================

DROP POLICY IF EXISTS project_teams_update ON paliad.project_teams;
CREATE POLICY project_teams_update
    ON paliad.project_teams FOR UPDATE
    USING (paliad.can_see_project(project_id))
    WITH CHECK (paliad.can_see_project(project_id));

DROP POLICY IF EXISTS project_teams_insert ON paliad.project_teams;
CREATE POLICY project_teams_insert
    ON paliad.project_teams FOR INSERT
    WITH CHECK (
        user_id = auth.uid()
        OR paliad.can_see_project(project_id)
    );

DROP POLICY IF EXISTS project_teams_delete ON paliad.project_teams;
CREATE POLICY project_teams_delete
    ON paliad.project_teams FOR DELETE
    USING (
        paliad.can_see_project(project_id)
        AND (
            user_id = auth.uid()
            OR EXISTS (
                SELECT 1 FROM paliad.users u
                 WHERE u.id = auth.uid()
                   AND u.global_role = 'global_admin'
            )
        )
    );

-- ============================================================================
-- 4. Drop the predicate function.
-- ============================================================================

DROP FUNCTION IF EXISTS paliad.effective_project_admin(uuid, uuid);
