-- =============================================================================
-- VIEW: vw_user_identity_roles
-- PURPOSE: Resolves the complete role matrix for any authenticated partner.
--          Used by fn_get_user_session_context to build the session context.
-- FIX:     is_student now checks student_profiles directly instead of
--          always returning true (partner_id IS NOT NULL is always true).
-- =============================================================================

CREATE OR REPLACE VIEW public.vw_user_identity_roles AS
SELECT
    p.partner_id,
    p.name,
    p.surname,
    p.email,
    p.phone,
    p.country,
    p.zinzino_range,
    CASE WHEN sa.partner_id IS NOT NULL AND sa.status = 'ACTIVE'::text             THEN true ELSE false END AS is_superadmin,
    CASE WHEN pp.partner_id IS NOT NULL AND pp.status = 'ACTIVE'::text             THEN true ELSE false END AS is_professor,
    CASE WHEN tp.partner_id IS NOT NULL AND tp.status::text = 'ACTIVE'::text       THEN true ELSE false END AS is_tutor,
    CASE WHEN sp.partner_id IS NOT NULL AND sp.status = 'ACTIVE'::enrollment_status THEN true ELSE false END AS is_student
FROM partners p
LEFT JOIN superadmin_profiles sa ON p.partner_id = sa.partner_id
LEFT JOIN professor_profiles  pp ON p.partner_id = pp.partner_id
LEFT JOIN tutor_profiles      tp ON p.partner_id = tp.partner_id
LEFT JOIN student_profiles    sp ON p.partner_id = sp.partner_id;
