import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

/**
 * GET /api/exercises/[id]
 *
 * Get the exercise + a paginated slice of its workout history.
 *
 * Query params:
 *   - offset: number (default 0) — how many workouts to skip
 *   - limit:  number (default 25, max 100) — page size
 *
 * Response shape:
 *   { exercise, history: [{workout:{id,date,name}, sets:[...]}], hasMore: bool }
 *
 * Pagination uses the take: limit + 1 trick — fetch one extra row, slice
 * it off, and use its presence to set hasMore. Avoids a second COUNT()
 * query.
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const sp = request.nextUrl.searchParams;
    const limit = Math.min(parseInt(sp.get("limit") || "25"), 100);
    const offset = Math.max(parseInt(sp.get("offset") || "0"), 0);

    const exercise = await prisma.exercise.findFirst({
      where: {
        id: params.id,
        userId: user.id,
      },
    });

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

    // Pull workouts that contain this exercise, with only the matching
    // set logs included. Cleaner + faster than fetching all set logs
    // and grouping in JS — Prisma generates a single SQL with the
    // (userId, deletedAt, date) composite index doing the heavy lift.
    const rows = await prisma.workout.findMany({
      where: {
        userId: user.id,
        deletedAt: null,
        setLogs: { some: { exerciseId: params.id } },
      },
      select: {
        id: true,
        date: true,
        name: true,
        setLogs: {
          where: { exerciseId: params.id },
          orderBy: { setNumber: "asc" },
        },
      },
      orderBy: { date: "desc" },
      take: limit + 1,
      skip: offset,
    });

    const hasMore = rows.length > limit;
    const history = rows.slice(0, limit).map((w) => ({
      workout: { id: w.id, date: w.date, name: w.name },
      sets: w.setLogs,
    }));

    return NextResponse.json({ exercise, history, hasMore });
  } catch (error) {
    console.error("GET /api/exercises/[id] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

/**
 * PATCH /api/exercises/[id]
 * Edit exercise details
 */
const updateExerciseSchema = z.object({
  name: z.string().min(1).optional(),
  type: z.string().min(1).optional(),
  muscleGroups: z.array(z.string()).optional(),
  description: z.string().optional(),
  inputFields: z.array(z.string().min(1)).optional(),
  defaultWeightUnit: z.string().nullable().optional(),
});

export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const exercise = await prisma.exercise.findFirst({
      where: {
        id: params.id,
        userId: user.id,
      },
    });

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

    const body = await request.json();
    const validated = updateExerciseSchema.parse(body);

    const data: any = {};
    if (validated.name !== undefined) data.name = validated.name;
    if (validated.type !== undefined) data.type = validated.type;
    if (validated.description !== undefined) data.description = validated.description;
    if (validated.muscleGroups !== undefined)
      data.muscleGroups = JSON.stringify(validated.muscleGroups);
    if (validated.inputFields !== undefined)
      data.inputFields = JSON.stringify(validated.inputFields);
    if (validated.defaultWeightUnit !== undefined)
      data.defaultWeightUnit = validated.defaultWeightUnit;

    // Flip isCustom -> true on any user edit. The boot-time
    // ensureExerciseLibrary reconciliation only updates rows where
    // isCustom = 0, so this preserves the user's intent: once they've
    // edited a library exercise, the maintainer can no longer
    // overwrite their changes via a curated-library refresh.
    data.isCustom = true;

    const updated = await prisma.exercise.update({
      where: { id: params.id },
      data,
    });

    return NextResponse.json(updated);
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Invalid data", details: error.errors },
        { status: 400 }
      );
    }
    console.error("PATCH /api/exercises/[id] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

/**
 * DELETE /api/exercises/[id]
 */
export async function DELETE(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const exercise = await prisma.exercise.findFirst({
      where: {
        id: params.id,
        userId: user.id,
      },
    });

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

    await prisma.setLog.deleteMany({
      where: { exerciseId: params.id },
    });

    await prisma.exercise.delete({
      where: { id: params.id },
    });

    return NextResponse.json({ message: "Exercise deleted successfully" });
  } catch (error) {
    console.error("DELETE /api/exercises/[id] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
