-- Reverse t-paliad-160 M1: drop the new columns + restore the previous
-- paliad.approval_policy_effective() shape from migration 062.
--
-- M1 is additive in code (dual-read), so this down migration restores the
-- previous resolver semantics (project row wins outright, MAX(level) over
-- ancestors+unit defaults). The required_role column was never dropped
-- in M1 so the legacy values are still the source of truth.

DROP FUNCTION IF EXISTS paliad.approval_policy_effective(uuid, text, text);

CREATE OR REPLACE FUNCTION paliad.approval_policy_effective(
    p_project_id  uuid,
    p_entity_type text,
    p_lifecycle   text
) RETURNS TABLE (
    required_role text,
    source        text,
    source_id     uuid
)
LANGUAGE plpgsql STABLE AS $$
BEGIN
    RETURN QUERY
    SELECT ap.required_role, 'project'::text AS source, ap.project_id AS source_id
      FROM paliad.approval_policies ap
     WHERE ap.project_id = p_project_id
       AND ap.entity_type = p_entity_type
       AND ap.lifecycle_event = p_lifecycle;
    IF FOUND THEN
        RETURN;
    END IF;

    RETURN QUERY
    WITH path AS (
        SELECT string_to_array(p.path, '.')::uuid[] AS ids
          FROM paliad.projects p WHERE p.id = p_project_id
    ),
    ancestor_rows AS (
        SELECT ap.required_role,
               'ancestor'::text AS src,
               ap.project_id AS sid,
               paliad.approval_role_level(ap.required_role) AS lvl
          FROM paliad.approval_policies ap, path
         WHERE ap.project_id = ANY(path.ids)
           AND ap.project_id <> p_project_id
           AND ap.entity_type = p_entity_type
           AND ap.lifecycle_event = p_lifecycle
    ),
    unit_rows AS (
        SELECT ap.required_role,
               'unit_default'::text AS src,
               ap.partner_unit_id AS sid,
               paliad.approval_role_level(ap.required_role) AS lvl
          FROM paliad.approval_policies ap
          JOIN paliad.project_partner_units ppu
            ON ppu.partner_unit_id = ap.partner_unit_id
         WHERE ppu.project_id = p_project_id
           AND ap.entity_type = p_entity_type
           AND ap.lifecycle_event = p_lifecycle
    )
    SELECT a.required_role, a.src, a.sid
      FROM (
            SELECT * FROM ancestor_rows
            UNION ALL
            SELECT * FROM unit_rows
           ) AS a
     ORDER BY a.lvl DESC, a.src ASC
     LIMIT 1;
END;
$$;

ALTER TABLE paliad.approval_policies
    DROP CONSTRAINT IF EXISTS approval_policies_min_role_xor_required;
ALTER TABLE paliad.approval_policies
    DROP CONSTRAINT IF EXISTS approval_policies_min_role_check;
ALTER TABLE paliad.approval_policies
    DROP COLUMN IF EXISTS requires_approval,
    DROP COLUMN IF EXISTS min_role;
