import { NextResponse } from "next/server";
import { DepartmentKey, PmTemplateState } 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 CreateTemplateBody = {
  assetId?: string;
  title?: string;
  description?: string | null;
  cadenceDays?: number | null;
  cadenceHours?: number | null;
  state?: PmTemplateState;
};

const VALID_STATES = new Set<PmTemplateState>([
  PmTemplateState.draft,
  PmTemplateState.active,
  PmTemplateState.archived,
]);

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 templates = await prisma.pmTemplate.findMany({
    where: {
      asset: {
        department: DepartmentKey.operaciones,
      },
    },
    include: {
      asset: {
        select: {
          id: true,
          name: true,
          assetCode: true,
        },
      },
    },
    orderBy: [{ updatedAt: "desc" }],
    take: 500,
  });

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

export async function POST(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 create templates." }, { status: 403 });
  }

  const body = (await request.json()) as CreateTemplateBody;
  if (!body.assetId || !body.title?.trim()) {
    return NextResponse.json({ error: "assetId and title are required." }, { status: 400 });
  }
  const asset = await prisma.factoryAsset.findFirst({
    where: {
      id: body.assetId,
      department: DepartmentKey.operaciones,
    },
    select: { id: true },
  });
  if (!asset) {
    return NextResponse.json({ error: "Asset not found in operations department." }, { status: 404 });
  }

  const template = await prisma.pmTemplate.create({
    data: {
      assetId: body.assetId,
      title: body.title.trim(),
      description: body.description?.trim() || null,
      cadenceDays: body.cadenceDays ? Math.max(1, Math.round(body.cadenceDays)) : null,
      cadenceHours: body.cadenceHours ? Math.max(1, Math.round(body.cadenceHours)) : null,
      state: body.state && VALID_STATES.has(body.state) ? body.state : PmTemplateState.active,
      createdById: session.user.id,
    },
  });

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