import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { getDatabase } from "@/lib/database";
import { ensureUserSynced } from "@/lib/sync-user";
import log from "@/lib/logger";

/**
 * DELETE /api/trainer-client/[id]
 * Delete (deactivate) a trainer-client assignment
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { userId: authUserId } = await auth();
    if (!authUserId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const db = await getDatabase();
    const currentUser = await ensureUserSynced(authUserId, db);

    if (!currentUser) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    // Only admins can delete assignments
    if (currentUser.role !== "admin" && currentUser.role !== "superAdmin") {
      return NextResponse.json(
        { error: "Only admins can remove trainer-client assignments" },
        { status: 403 },
      );
    }

    const { id } = await params;

    const allAssignments = await db.getAllTrainerClientAssignments();
    const assignment = allAssignments.find((a) => a.id === id);

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

    if (currentUser.role !== "superAdmin") {
      if (!currentUser.gymId) {
        return NextResponse.json({ error: "No gym assigned" }, { status: 403 });
      }

      const [trainer, client] = await Promise.all([
        db.getUserById(assignment.trainerId),
        db.getUserById(assignment.clientId),
      ]);

      if (
        !trainer ||
        !client ||
        trainer.gymId !== currentUser.gymId ||
        client.gymId !== currentUser.gymId
      ) {
        return NextResponse.json(
          { error: "Cannot modify assignments from other gyms" },
          { status: 403 },
        );
      }
    }

    // Deactivate the assignment
    const result = await db.deactivateTrainerClientAssignment(id);

    if (!result) {
      return NextResponse.json(
        { error: "Failed to deactivate assignment" },
        { status: 500 },
      );
    }

    log.info("Trainer-client assignment deactivated", {
      assignmentId: id,
      deactivatedBy: currentUser.id,
    });

    return NextResponse.json({
      success: true,
      message: "Assignment deactivated successfully",
    });
  } catch (error) {
    log.error("Failed to delete trainer-client assignment", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
