import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { Post } from '../../posts/schemas/post.schema';
import { User } from '../../users/schemas/user.schema';

export type CollaborationRequestDocument = HydratedDocument<CollaborationRequest>;
export const COLLABORATION_TYPES = ['duet', 'arrangement', 'composition'] as const;
export type CollaborationType = (typeof COLLABORATION_TYPES)[number];

export const COLLABORATION_ATTACHMENT_TYPES = ['audio', 'demo', 'file'] as const;
export type CollaborationAttachmentType = (typeof COLLABORATION_ATTACHMENT_TYPES)[number];

export const COLLABORATION_REQUEST_STATUSES = [
  'pending',
  'approved',
  'rejected',
  'cancelled',
] as const;
export type CollaborationRequestStatus = (typeof COLLABORATION_REQUEST_STATUSES)[number];

@Schema({ timestamps: true, versionKey: false })
export class CollaborationRequest {
  @Prop({
    type: Types.ObjectId,
    ref: Post.name,
    required: false,
    default: null,
    index: true,
  })
  postId?: Types.ObjectId | null;

  @Prop({ type: Types.ObjectId, ref: User.name, required: true, index: true })
  requesterId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: User.name, required: true, index: true })
  targetUserId!: Types.ObjectId;

  @Prop({
    type: String,
    enum: COLLABORATION_REQUEST_STATUSES,
    default: 'pending',
    index: true,
  })
  status!: CollaborationRequestStatus;

  @Prop({
    type: String,
    enum: COLLABORATION_TYPES,
    required: false,
    default: null,
    index: true,
  })
  collaborationType?: CollaborationType | null;

  @Prop({ type: String, required: false, default: '', trim: true, maxlength: 1000 })
  message!: string;

  @Prop({ type: String, required: false, default: '', trim: true, maxlength: 500 })
  attachmentUrl!: string;

  @Prop({
    type: String,
    enum: COLLABORATION_ATTACHMENT_TYPES,
    required: false,
    default: null,
  })
  attachmentType?: CollaborationAttachmentType | null;
}

export const CollaborationRequestSchema = SchemaFactory.createForClass(CollaborationRequest);
CollaborationRequestSchema.index({ postId: 1, targetUserId: 1, status: 1 });
CollaborationRequestSchema.index({ targetUserId: 1, status: 1, createdAt: -1 });
CollaborationRequestSchema.index({ requesterId: 1, status: 1, createdAt: -1 });
