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

const SeedExerciseSchema = z.object({
  name: z.string().min(1),
  type: z.string().min(1).default("other"),
  muscleGroups: z.array(z.string()).optional().default([]),
  inputFields: z.array(z.string().min(1)).optional().default(["sets", "reps", "weight"]),
  defaultWeightUnit: z.string().nullable().optional(),
});

const SeedPayloadSchema = z.object({
  exercises: z.array(SeedExerciseSchema).min(1),
});

function normalizeToken(value: string): string {
  return value.trim().toLowerCase();
}

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

    const body = await request.json();
    const parsed = SeedPayloadSchema.parse(body);

    const existingExercises = await prisma.exercise.findMany({
      where: { userId: user.id },
      select: { name: true },
    });
    const existingNames = new Set(existingExercises.map((x) => normalizeToken(x.name)));

    let created = 0;
    let skipped = 0;
    const errors: Array<{ name: string; error: string }> = [];

    for (const item of parsed.exercises) {
      const rawName = item.name.trim();
      const nameKey = normalizeToken(rawName);
      if (!rawName) continue;

      if (existingNames.has(nameKey)) {
        skipped += 1;
        continue;
      }

      const muscleGroups = Array.from(
        new Set(item.muscleGroups.map((v) => normalizeToken(v)).filter(Boolean))
      );
      let inputFields = Array.from(
        new Set(item.inputFields.map((v) => normalizeToken(v)).filter(Boolean))
      );
      if (!inputFields.includes("sets")) {
        inputFields = ["sets", ...inputFields];
      }

      try {
        await prisma.exercise.create({
          data: {
            userId: user.id,
            name: rawName,
            type: normalizeToken(item.type || "other"),
            muscleGroups: JSON.stringify(muscleGroups),
            inputFields: JSON.stringify(inputFields),
            defaultWeightUnit: item.defaultWeightUnit ?? null,
            isCustom: true,
          } as any,
        });
        existingNames.add(nameKey);
        created += 1;
      } catch (error) {
        errors.push({
          name: rawName,
          error: error instanceof Error ? error.message : "Unknown error",
        });
      }
    }

    return NextResponse.json({
      success: true,
      created,
      skipped,
      errors,
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Invalid seed payload", details: error.errors },
        { status: 400 }
      );
    }

    console.error("POST /api/import/exercises/seed error:", error);
    return NextResponse.json(
      { error: "Failed to process exercise seed" },
      { status: 500 }
    );
  }
}
