-- RLS policies for timetable-related tables (Term, Holiday, SchoolTimetableSlot, TimetableTemplate, TimetableEntry)

-- Helper condition: teacher can manage schools where they are linked and not managed (independent/agency)
CREATE OR REPLACE FUNCTION teacher_can_manage_school(_school_id text)
RETURNS boolean
LANGUAGE sql STABLE
AS $$
  SELECT EXISTS (
    SELECT 1
    FROM "TeacherSchool"
    WHERE "teacherId" = requesting_user_id()
      AND "schoolId" = _school_id
      AND "isManaged" = false
  );
$$;

-- TERM
CREATE POLICY "Admins have full access on Term"
ON "Term"
FOR ALL
USING (is_admin())
WITH CHECK (is_admin());

CREATE POLICY "Teachers manage terms for their schools"
ON "Term"
FOR ALL
TO authenticated
USING (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
)
WITH CHECK (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
);

-- HOLIDAY
CREATE POLICY "Admins have full access on Holiday"
ON "Holiday"
FOR ALL
USING (is_admin())
WITH CHECK (is_admin());

CREATE POLICY "Teachers manage holidays for their schools"
ON "Holiday"
FOR ALL
TO authenticated
USING (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
)
WITH CHECK (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
);

-- SCHOOL TIMETABLE SLOT
CREATE POLICY "Admins have full access on SchoolTimetableSlot"
ON "SchoolTimetableSlot"
FOR ALL
USING (is_admin())
WITH CHECK (is_admin());

CREATE POLICY "Teachers manage slots for their schools"
ON "SchoolTimetableSlot"
FOR ALL
TO authenticated
USING (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
)
WITH CHECK (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
);

-- TIMETABLE TEMPLATE
CREATE POLICY "Admins have full access on TimetableTemplate"
ON "TimetableTemplate"
FOR ALL
USING (is_admin())
WITH CHECK (is_admin());

CREATE POLICY "Teachers manage templates for their schools"
ON "TimetableTemplate"
FOR ALL
TO authenticated
USING (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
)
WITH CHECK (
  requesting_user_role() = 'teacher'
  AND teacher_can_manage_school("schoolId")
);

-- TIMETABLE ENTRY
CREATE POLICY "Admins have full access on TimetableEntry"
ON "TimetableEntry"
FOR ALL
USING (is_admin())
WITH CHECK (is_admin());

CREATE POLICY "Teachers manage entries for their schools"
ON "TimetableEntry"
FOR ALL
TO authenticated
USING (
  requesting_user_role() = 'teacher'
  AND EXISTS (
    SELECT 1
    FROM "TimetableTemplate" tt
    WHERE tt.id = "timetableTemplateId"
      AND teacher_can_manage_school(tt."schoolId")
  )
)
WITH CHECK (
  requesting_user_role() = 'teacher'
  AND EXISTS (
    SELECT 1
    FROM "TimetableTemplate" tt
    WHERE tt.id = "timetableTemplateId"
      AND teacher_can_manage_school(tt."schoolId")
  )
);

