import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";

type Params = { params: Promise<{ id: string }> };

interface WeekInput {
  id?: number;
  weekNo?: number;
  topic?: string;
  homework?: string | null;
  isDone?: boolean;
}

function deriveStatus(completed: number, total: number): string {
  if (total > 0 && completed >= total) return "COMPLETED";
  if (completed > 0) return "IN_PROGRESS";
  return "PLANNED";
}

/** Update a lesson plan; `weeks` (when provided) replaces the breakdown. */
export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  try {
    const body = await req.json();
    const plan = await prisma.lessonPlan.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const chapter = String(body.chapter ?? plan.chapter).trim();
    if (!chapter) return NextResponse.json({ error: "Chapter required" }, { status: 400 });

    const totalPeriods =
      body.totalPeriods !== undefined ? Math.max(0, Number(body.totalPeriods) || 0) : plan.totalPeriods;
    const completedPeriods =
      body.completedPeriods !== undefined
        ? Math.max(0, Number(body.completedPeriods) || 0)
        : plan.completedPeriods;

    const data: Record<string, unknown> = {
      chapter,
      topics: body.topics !== undefined ? String(body.topics).trim() || null : plan.topics,
      staffId: body.staffId !== undefined ? (body.staffId ? Number(body.staffId) : null) : plan.staffId,
      classItemId: body.classItemId !== undefined ? (body.classItemId ? Number(body.classItemId) : null) : plan.classItemId,
      sectionItemId:
        body.sectionItemId !== undefined
          ? body.sectionItemId
            ? Number(body.sectionItemId)
            : null
          : plan.sectionItemId,
      subjectItemId:
        body.subjectItemId !== undefined
          ? body.subjectItemId
            ? Number(body.subjectItemId)
            : null
          : plan.subjectItemId,
      startDate: body.startDate ? new Date(String(body.startDate)) : plan.startDate,
      endDate:
        body.endDate !== undefined ? (body.endDate ? new Date(String(body.endDate)) : null) : plan.endDate,
      totalPeriods,
      completedPeriods: Math.min(completedPeriods, totalPeriods || completedPeriods),
      status: deriveStatus(Math.min(completedPeriods, totalPeriods || completedPeriods), totalPeriods),
    };

    const weeks: WeekInput[] | undefined = Array.isArray(body.weeks) ? body.weeks : undefined;

    await prisma.$transaction(async (tx) => {
      await tx.lessonPlan.update({ where: { id: plan.id }, data });

      if (weeks) {
        await tx.lessonWeek.deleteMany({ where: { lessonPlanId: plan.id } });
        await tx.lessonWeek.createMany({
          data: weeks
            .filter((w) => String(w.topic ?? "").trim())
            .map((w, i) => ({
              institutionId: session.institutionId!,
              lessonPlanId: plan.id,
              weekNo: Number(w.weekNo) || i + 1,
              topic: String(w.topic).trim(),
              homework: String(w.homework ?? "").trim() || null,
              isDone: !!w.isDone,
            })),
        });
      }
    });

    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update lesson plan" }, { status: 500 });
  }
}

/** Delete a lesson plan (weeks cascade). */
export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;
  const plan = await prisma.lessonPlan.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
  await prisma.lessonPlan.delete({ where: { id: plan.id } });
  return NextResponse.json({ success: true });
}
