import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { resolveManagedFileUrl } from '../../../common/utils/public-url.util';
import { User } from '../../users/schemas/user.schema';

export type AiMusicArchiveDocument = HydratedDocument<AiMusicArchive>;

export enum AiMusicArchiveType {
  TEXT_TO_MUSIC = 'text_to_music',
  AUDIO_TO_MUSIC = 'audio_to_music',
  OTHER = 'other',
}

@Schema({ timestamps: true, versionKey: false })
export class AiMusicArchive {
  @Prop({ type: Types.ObjectId, ref: User.name, required: true, index: true })
  userId!: Types.ObjectId;

  @Prop({
    type: String,
    enum: Object.values(AiMusicArchiveType),
    default: AiMusicArchiveType.TEXT_TO_MUSIC,
    index: true,
  })
  type!: AiMusicArchiveType;

  @Prop({ required: true, trim: true, maxlength: 120 })
  title!: string;

  @Prop({ default: '', trim: true, maxlength: 500 })
  prompt!: string;

  @Prop({ default: '', trim: true, maxlength: 80 })
  tag!: string;

  @Prop({ required: true })
  audioUrl!: string;

  @Prop({ default: '' })
  storageKey!: string;

  @Prop({ type: Number, min: 0, default: null })
  durationSeconds!: number | null;

  @Prop({ default: '' })
  mimeType!: string;

  @Prop({ default: 0, min: 0 })
  sizeBytes!: number;

  @Prop({ type: [Number], default: [] })
  waveformPeaks!: number[];

  @Prop({ default: false, index: true })
  isDeleted!: boolean;
}

export const AiMusicArchiveSchema = SchemaFactory.createForClass(AiMusicArchive);

AiMusicArchiveSchema.index({ userId: 1, isDeleted: 1, createdAt: -1 });

const transformManagedArchiveFiles = (_doc: unknown, ret: any) => {
  ret.id = ret._id?.toString?.() ?? ret.id;
  ret.audioUrl = resolveManagedFileUrl(ret.audioUrl);
  return ret;
};

AiMusicArchiveSchema.set('toJSON', { transform: transformManagedArchiveFiles });
AiMusicArchiveSchema.set('toObject', { transform: transformManagedArchiveFiles });
