import { NextResponse } from "next/server";
import { DepartmentKey, ReminderEventState } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canAccessOperations, canManageOperations } from "@/lib/operations";

type PatchReminderBody = {
  reminderId?: string;
  state?: ReminderEventState;
};

const VALID_STATES = new Set<ReminderEventState>([
  ReminderEventState.queued,
  ReminderEventState.sent,
  ReminderEventState.acknowledged,
  ReminderEventState.escalated,
  ReminderEventState.failed,
]);

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessOperations(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const reminders = await prisma.reminderEvent.findMany({
    where: {
      workOrder: {
        asset: {
          department: DepartmentKey.operaciones,
        },
      },
    },
    include: {
      workOrder: {
        include: {
          asset: {
            select: {
              name: true,
              assetCode: true,
            },
          },
        },
      },
    },
    orderBy: [{ remindAt: "asc" }],
    take: 300,
  });

  return NextResponse.json({ ok: true, reminders });
}

export async function PATCH(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageOperations(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/operations leader can update reminders." }, { status: 403 });
  }

  const body = (await request.json()) as PatchReminderBody;
  if (!body.reminderId || !body.state || !VALID_STATES.has(body.state)) {
    return NextResponse.json({ error: "reminderId and valid state are required." }, { status: 400 });
  }
  const scopedReminder = await prisma.reminderEvent.findFirst({
    where: {
      id: body.reminderId,
      workOrder: {
        asset: {
          department: DepartmentKey.operaciones,
        },
      },
    },
    select: { id: true },
  });
  if (!scopedReminder) {
    return NextResponse.json({ error: "Reminder not found in operations department." }, { status: 404 });
  }

  const reminder = await prisma.reminderEvent.update({
    where: { id: scopedReminder.id },
    data: {
      state: body.state,
      acknowledgedAt: body.state === ReminderEventState.acknowledged ? new Date() : null,
    },
  });

  return NextResponse.json({ ok: true, reminder });
}
