import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Types, Schema as MongooseSchema } from "mongoose";

export type WorkoutSessionDocument = WorkoutSession & Document;

// Kept identical to TrainingPlan's set structure.
@Schema({ _id: false })
export class WorkoutSet {
  // Dynamic values keyed by the category's field keys.
  // e.g. strength -> { reps: 12, weight: 20, break_duration: 60 }
  //      time     -> { duration: 60, break_duration: 30 }
  //      cardio   -> { distance: 1.5, duration: 600 }
  @Prop({ type: MongooseSchema.Types.Mixed, default: {} })
  values: Record<string, number | string>;
}

export const WorkoutSetSchema = SchemaFactory.createForClass(WorkoutSet);

// Kept identical to TrainingPlan's exercise structure.
@Schema({ _id: false })
export class WorkoutExercise {
  @Prop({ type: Types.ObjectId, ref: "Exercise", required: true })
  exercise_id: Types.ObjectId;

  @Prop({ type: [WorkoutSetSchema], default: [] })
  sets: WorkoutSet[];
}

export const WorkoutExerciseSchema =
  SchemaFactory.createForClass(WorkoutExercise);

@Schema({ timestamps: true, strict: true })
export class WorkoutSession {
  @Prop({
    type: Types.ObjectId,
    ref: "User",
    required: true,
  })
  user: Types.ObjectId;

  @Prop({
    type: Types.ObjectId,
    ref: "TrainingPlan",
    required: true,
  })
  trainingPlan: Types.ObjectId;

  @Prop({
    type: Types.ObjectId,
    required: true,
  })
  dayId: Types.ObjectId;

  @Prop({ type: Date, required: true })
  startedAt: Date;

  @Prop({ type: Date })
  endedAt: Date;

  @Prop({ type: Number })
  durationInSeconds: number;

  // Denormalized running totals so the latest session alone can drive the
  // plan's progress UI without re-aggregating.
  // sessionNumber = this session's global ordinal (total sessions so far).
  @Prop({ type: Number, default: null })
  sessionNumber: number;

  // Cumulative training time across all sessions, including this one.
  @Prop({ type: Number, default: 0 })
  totalDurationInSeconds: number;

  @Prop({ type: String })
  notes: string;

  // Copy of the exercises exactly as received from the frontend
  // (same structure as TrainingPlan).
  @Prop({ type: [WorkoutExerciseSchema], default: [] })
  exercises: WorkoutExercise[];

  @Prop({ default: null })
  deleted_at: Date | null;
}

export const WorkoutSessionSchema =
  SchemaFactory.createForClass(WorkoutSession);
