import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Types } from "mongoose";
import { User } from "src/user/schemas/user.schema";
import { Challenges } from "./challenges.schema";
import { ChallengesUser } from "./challengesUser.schema";
import { ChallengeMode } from "src/common/enums/challenges.enum";

/**
 * A completed challenge — a materialized "achievement". This is a DERIVED
 * projection: `challengesusers` remains the source of truth for attempts and
 * live progress, and a completion is upserted here (keyed by user+challenge) at
 * every point completion is detected. Because it lives in its own collection it
 * survives re-joining / quitting the challenge, and the unique key makes re-
 * completing simply override the previous record (one row per challenge).
 *
 * Display fields are snapshotted so reads need no join and no recompute.
 */
@Schema({ timestamps: true })
export class Achievement {
  @Prop({ type: Types.ObjectId, ref: User.name, required: true })
  user_id: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: Challenges.name, required: true })
  challenge_id: Types.ObjectId;

  // the attempt (challengesusers record) whose completion this represents
  @Prop({ type: Types.ObjectId, ref: ChallengesUser.name })
  membership_id: Types.ObjectId;

  @Prop({ type: String, enum: Object.values(ChallengeMode) })
  type: ChallengeMode;

  // ── snapshot of the challenge, as it was when completed ──
  @Prop({ type: Object })
  title: Record<string, string>;

  @Prop({ type: Object })
  short_desc: Record<string, string>;

  @Prop({ type: Object })
  focus: Record<string, string[]>;

  @Prop({ type: Object })
  level: Record<string, string>;

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

  @Prop({ type: Object, default: null })
  goal: Record<string, any>;

  @Prop({ type: Number, default: 0 })
  duration: number;

  // the final progress summary (habit: { target, completed }; perf/volume: the record)
  @Prop({ type: Object, default: null })
  result: Record<string, any>;

  @Prop({ type: Date, default: null })
  started_at: Date;

  @Prop({ type: Date, default: null })
  completed_at: Date;
}

export type AchievementDocument = Achievement & Document;
export const AchievementSchema = SchemaFactory.createForClass(Achievement);

// one achievement per user+challenge — re-completing upserts (overrides) it.
AchievementSchema.index({ user_id: 1, challenge_id: 1 }, { unique: true });
