import { prisma } from "../prisma";
import { Exercise, SetLog } from "@prisma/client";

/**
 * Get all exercises for a user
 */
export async function getExercises(userId: string): Promise<Exercise[]> {
  return prisma.exercise.findMany({
    where: { userId },
    orderBy: {
      name: "asc",
    },
  });
}

/**
 * Get a single exercise by ID
 */
export async function getExerciseById(id: string): Promise<Exercise | null> {
  return prisma.exercise.findUnique({
    where: { id },
  });
}

/**
 * Create a new exercise
 */
export async function createExercise(data: {
  userId: string;
  name: string;
  type?: string;
  description?: string;
  muscleGroups?: string;
  inputFields?: string;
  defaultWeightUnit?: string | null;
  isCustom?: boolean;
}): Promise<Exercise> {
  return prisma.exercise.create({
    data: {
      userId: data.userId,
      name: data.name,
      type: data.type || "other",
      description: data.description,
      muscleGroups: data.muscleGroups || JSON.stringify([]),
      isCustom: data.isCustom || false,
      // These fields exist in schema but Prisma client may not be regenerated yet
      ...(data.inputFields ? { inputFields: data.inputFields } : {}),
      ...(data.defaultWeightUnit ? { defaultWeightUnit: data.defaultWeightUnit } : {}),
    } as any,
  });
}

/**
 * Get all set logs for an exercise (history)
 */
export async function getExerciseHistory(
  exerciseId: string,
  userId: string
): Promise<SetLog[]> {
  return prisma.setLog.findMany({
    where: {
      exerciseId,
      workout: {
        userId,
        deletedAt: null,
      },
    },
    orderBy: {
      createdAt: "desc",
    },
  });
}

/**
 * Get the personal best (highest weight) for an exercise
 */
export async function getPersonalBest(
  exerciseId: string,
  userId: string
): Promise<{ weight: number; reps: number; date: Date } | null> {
  const set = await prisma.setLog.findFirst({
    where: {
      exerciseId,
      workout: {
        userId,
        deletedAt: null,
      },
    },
    orderBy: [
      {
        weight: "desc",
      },
      {
        reps: "desc",
      },
    ],
    select: {
      weight: true,
      reps: true,
      createdAt: true,
    },
  });

  if (!set) {
    return null;
  }

  return {
    weight: set.weight || 0,
    reps: set.reps || 0,
    date: set.createdAt,
  };
}
