import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import type { RecurringType } from "@/lib/token/scheduling";

/**
 * GET  /api/token/schedule         — List upcoming maintenance windows.
 * POST /api/token/schedule         — Create a new maintenance window.
 * DELETE /api/token/schedule?id=x  — Delete a maintenance window.
 *
 * Auth: NextAuth session required for all methods.
 */

const VALID_RECURRING: RecurringType[] = ["none", "daily", "weekly"];

/* ── GET ──────────────────────────────────────────────────────────────── */

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

  const now = new Date();

  const windows = await db.maintenanceWindow.findMany({
    where: {
      userId: session.user.id,
      OR: [
        { recurring: "none", endTime: { gt: now } },
        { recurring: { not: "none" } },
      ],
    },
    orderBy: { startTime: "asc" },
  });

  logger.debug(
    {
      action: "maintenance_windows_list",
      user_id: session.user.id,
      count: windows.length,
    },
    "Listed maintenance windows",
  );

  return NextResponse.json({ windows });
}

/* ── POST ─────────────────────────────────────────────────────────────── */

interface CreateBody {
  deviceId: string;
  startTime: string;
  endTime: string;
  reason?: string;
  recurring?: RecurringType;
}

export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let body: CreateBody;
  try {
    body = (await req.json()) as CreateBody;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const { deviceId, startTime, endTime, reason, recurring } = body;

  // Required fields
  if (!deviceId || !startTime || !endTime) {
    return NextResponse.json(
      { error: "deviceId, startTime, and endTime are required" },
      { status: 400 },
    );
  }

  // Parse dates
  const start = new Date(startTime);
  const end = new Date(endTime);

  if (isNaN(start.getTime()) || isNaN(end.getTime())) {
    return NextResponse.json(
      { error: "startTime and endTime must be valid ISO 8601 dates" },
      { status: 400 },
    );
  }

  // Validate: startTime < endTime
  if (start >= end) {
    return NextResponse.json(
      { error: "startTime must be before endTime" },
      { status: 400 },
    );
  }

  // Validate: endTime in the future (only for non-recurring)
  const recType = recurring ?? "none";
  if (recType === "none" && end <= new Date()) {
    return NextResponse.json(
      { error: "endTime must be in the future" },
      { status: 400 },
    );
  }

  // Validate recurring type
  if (!VALID_RECURRING.includes(recType)) {
    return NextResponse.json(
      { error: `recurring must be one of: ${VALID_RECURRING.join(", ")}` },
      { status: 400 },
    );
  }

  // Validate: device belongs to user
  const device = await db.device.findFirst({
    where: { id: deviceId, userId: session.user.id },
  });
  if (!device) {
    return NextResponse.json(
      { error: "Device not found or not owned by user" },
      { status: 404 },
    );
  }

  const window = await db.maintenanceWindow.create({
    data: {
      deviceId,
      userId: session.user.id,
      startTime: start,
      endTime: end,
      reason: reason ?? "",
      recurring: recType,
    },
  });

  logger.info(
    {
      action: "maintenance_window_created",
      user_id: session.user.id,
      window_id: window.id,
      device_id: deviceId,
      recurring: recType,
    },
    "Maintenance window created",
  );

  return NextResponse.json({ window }, { status: 201 });
}

/* ── DELETE ────────────────────────────────────────────────────────────── */

export async function DELETE(req: NextRequest) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  if (!id) {
    return NextResponse.json({ error: "id parameter required" }, { status: 400 });
  }

  // Verify ownership
  const window = await db.maintenanceWindow.findFirst({
    where: { id, userId: session.user.id },
  });
  if (!window) {
    return NextResponse.json({ error: "Maintenance window not found" }, { status: 404 });
  }

  await db.maintenanceWindow.delete({ where: { id } });

  logger.info(
    {
      action: "maintenance_window_deleted",
      user_id: session.user.id,
      window_id: id,
    },
    "Maintenance window deleted",
  );

  return NextResponse.json({ deleted: true });
}
