import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

/**
 * POST /api/staff/users/[id]/notes
 * Add an admin note to a user account
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { content, category = "GENERAL", isPrivate = true } = body;

    // Validation
    if (!content || content.trim().length < 5) {
      return NextResponse.json(
        { error: "Note content required (minimum 5 characters)" },
        { status: 400 },
      );
    }

    if (content.length > 5000) {
      return NextResponse.json(
        { error: "Note content too long (maximum 5000 characters)" },
        { status: 400 },
      );
    }

    const validCategories = [
      "GENERAL",
      "BILLING",
      "SUPPORT",
      "COMPLIANCE",
      "TECHNICAL",
      "SALES",
    ];
    if (!validCategories.includes(category)) {
      return NextResponse.json({ error: "Invalid category" }, { status: 400 });
    }

    // Verify user exists
    const userExists = await prisma.users.findUnique({
      where: { id: params.id },
      select: { id: true, email: true },
    });

    if (!userExists) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    // Create admin note in Prisma
    const noteId = createId();
    const now = new Date();
    const note = await prisma.admin_notes.create({
      data: {
        id: noteId,
        userId: params.id,
        staffId: staffUser.id,
        content: content.trim(),
        category,
        isPrivate,
        updatedAt: now,
      },
    });

    // --- Convex data-source routing: sync admin note ---
    if (getDataSource("auth") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("auth/mutations:addUserNote", {
          userId: params.id,
          staffId: staffUser.id,
          content: content.trim(),
          category,
          isPrivate,
        });
      } catch (convexErr) {
        logger.warn("Convex admin note sync failed (non-critical)", {
          error: convexErr,
        });
      }
    }
    // --- End Convex routing ---

    logger.info("Admin note added", {
      userId: params.id,
      staffEmail: staffUser.email,
    });

    return NextResponse.json(
      {
        success: true,
        note,
      },
      { status: 201 },
    );
  } catch (error) {
    logger.error("Failed to create admin note", error);
    return NextResponse.json(
      { error: "Failed to create note" },
      { status: 500 },
    );
  }
}

/**
 * GET /api/staff/users/[id]/notes
 * Get all admin notes for a user
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const notes = await prisma.admin_notes.findMany({
      where: { userId: params.id },
      orderBy: { createdAt: "desc" },
      take: 100,
    });

    return NextResponse.json({ notes });
  } catch (error) {
    logger.error("Failed to fetch admin notes", error);
    return NextResponse.json(
      { error: "Failed to fetch notes" },
      { status: 500 },
    );
  }
}
