from api.services.exam_scheduler import available_session_starts_for_activity, schedule_exam_requirements
from api.tests.helpers import SchedulerTestCase, build_exam_world, post_signed, reload_activity

INFO_URL = "/api/admin/exam-activity/info"


class ExamActivityInfoHttpTests(SchedulerTestCase):
	def test_info_returns_activity_and_legal_session_starts(self):
		world = build_exam_world()
		response = post_signed(
			self.client,
			INFO_URL,
			{
				"exam_activity_id": world.activity.id,
				"exam_period_id": world.period.id,
			},
		)
		self.assertEqual(response.status_code, 200)
		body = response.json()
		self.assertEqual(body["code"], 200)
		info = body["data"]["info"]
		self.assertEqual(info["id"], world.activity.id)
		self.assertEqual(info["exam_period_id"], world.period.id)
		self.assertFalse(info["is_scheduled"])
		starts = body["data"]["session_start"]
		self.assertGreaterEqual(len(starts), 1)
		self.assertEqual(starts[0]["time_slot"], world.monday_slot())
		self.assertIn("scheduled_start_at", starts[0])
		self.assertIn("code", starts[0])


class ExamActivityInfoServiceTests(SchedulerTestCase):
	def test_empty_when_sibling_activities_disagree_on_time(self):
		world = build_exam_world()
		first = world.add_activity()
		second = world.add_activity()
		world.mark_scheduled(first, time_slot=world.monday_slot())
		world.mark_scheduled(second, time_slot=world.slot_for(2))
		starts = available_session_starts_for_activity(reload_activity(world.activity))
		self.assertEqual(starts, [])

	def test_empty_when_sibling_activities_disagree_on_location(self):
		world = build_exam_world()
		other_location = world.add_location()
		first = world.add_activity()
		second = world.add_activity()
		world.mark_scheduled(first, time_slot=world.monday_slot(), location=world.location)
		world.mark_scheduled(second, time_slot=world.monday_slot(), location=other_location)
		starts = available_session_starts_for_activity(reload_activity(world.activity))
		self.assertEqual(starts, [])

	def test_empty_when_no_rooms_have_capacity(self):
		world = build_exam_world(row=0, column=0)
		starts = available_session_starts_for_activity(world.activity)
		self.assertEqual(starts, [])

	def test_empty_when_no_session_starts(self):
		world = build_exam_world(create_session_start=False)
		starts = available_session_starts_for_activity(world.activity)
		self.assertEqual(starts, [])

	def test_self_preceding_returns_empty(self):
		world = build_exam_world()
		world.link_preceding(world.requirement, world.requirement)
		starts = available_session_starts_for_activity(world.activity)
		self.assertEqual(starts, [])

	def test_after_schedule_info_still_lists_current_slot_for_unscheduled_sibling(self):
		world = build_exam_world()
		sibling = world.add_activity()
		schedule_exam_requirements([world.activity.id], self.user.id)
		starts = available_session_starts_for_activity(sibling)
		self.assertEqual([item["time_slot"] for item in starts], [world.monday_slot()])
