"use server"

import { revalidatePath } from "next/cache"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"

import type { ActionState } from "@/shared/types/action-state"
import {
  createClassScheduleItem,
  updateClassScheduleItem,
  deleteClassScheduleItem,
} from "@/modules/scheduling/data-access-class-schedule"
import {
  CreateClassScheduleItemSchema,
  UpdateClassScheduleItemSchema,
  DeleteClassScheduleItemSchema,
} from "./schema"
import { toWeekday } from "./actions-shared"

export async function createClassScheduleItemAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    await requirePermission(Permissions.CLASS_SCHEDULE)

    const parsed = CreateClassScheduleItemSchema.safeParse({
      classId: formData.get("classId"),
      weekday: formData.get("weekday"),
      course: formData.get("course"),
      startTime: formData.get("startTime"),
      endTime: formData.get("endTime"),
      location: formData.get("location"),
    })
    if (!parsed.success) {
      return { success: false, message: "Invalid schedule item data" }
    }

    const { classId, weekday, course, startTime, endTime, location } = parsed.data

    try {
      const id = await createClassScheduleItem({
        classId,
        weekday: toWeekday(weekday),
        startTime,
        endTime,
        course,
        location: location ?? null,
      })
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Schedule item created successfully", data: id }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to create schedule item" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}

export async function updateClassScheduleItemAction(
  scheduleId: string,
  prevState: ActionState | null,
  formData: FormData
): Promise<ActionState> {
  try {
    await requirePermission(Permissions.CLASS_SCHEDULE)

    const parsed = UpdateClassScheduleItemSchema.safeParse({
      scheduleId,
      classId: formData.get("classId"),
      weekday: formData.get("weekday") || undefined,
      course: formData.get("course"),
      startTime: formData.get("startTime"),
      endTime: formData.get("endTime"),
      location: formData.get("location"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing or invalid schedule id" }
    }

    const { scheduleId: validatedScheduleId, classId, weekday, course, startTime, endTime, location } = parsed.data

    try {
      await updateClassScheduleItem(validatedScheduleId, {
        classId: classId ?? undefined,
        weekday: typeof weekday === "number" ? toWeekday(weekday) : undefined,
        startTime: startTime ?? undefined,
        endTime: endTime ?? undefined,
        course: course ?? undefined,
        location: location ?? undefined,
      })
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Schedule item updated successfully" }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to update schedule item" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}

export async function deleteClassScheduleItemAction(scheduleId: string): Promise<ActionState> {
  try {
    await requirePermission(Permissions.CLASS_SCHEDULE)

    const parsed = DeleteClassScheduleItemSchema.safeParse({ scheduleId })
    if (!parsed.success) {
      return { success: false, message: "Missing schedule id" }
    }

    try {
      await deleteClassScheduleItem(parsed.data.scheduleId)
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Schedule item deleted successfully" }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to delete schedule item" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}
