import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, SchemaTypes, Types } from 'mongoose';
import { PostShareTarget } from '../dto/share-post.dto';

export type PostShareDocument = HydratedDocument<PostShare>;

@Schema({ timestamps: true, versionKey: false, collection: 'postshares' })
export class PostShare {
  @Prop({ type: Types.ObjectId, required: true, index: true })
  userId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, required: true, index: true })
  postId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, required: true, index: true })
  originalAuthorId!: Types.ObjectId;

  @Prop({ type: SchemaTypes.Mixed, default: undefined })
  sharedFrom?: {
    type: 'user' | 'profile' | 'feed' | 'unknown';
    id?: string;
    name?: string;
    username?: string;
    avatar?: string;
  };

  @Prop({ type: String, enum: Object.values(PostShareTarget), default: PostShareTarget.PROFILE, index: true })
  target!: PostShareTarget;

  @Prop({ default: '', trim: true })
  channel!: string;

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

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

  @Prop({ type: Types.ObjectId, default: null })
  friendId?: Types.ObjectId | null;

  @Prop({ type: Types.ObjectId, default: null })
  sharedPostId?: Types.ObjectId | null;

  @Prop({ type: Types.ObjectId, default: null })
  conversationId?: Types.ObjectId | null;

  @Prop({ type: Types.ObjectId, default: null })
  messageId?: Types.ObjectId | null;

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

  @Prop({ type: Date, default: null, index: true })
  deletedAt?: Date | null;
}

export const PostShareSchema = SchemaFactory.createForClass(PostShare);

PostShareSchema.index({ userId: 1, createdAt: -1 });
PostShareSchema.index({ postId: 1, createdAt: -1 });
PostShareSchema.index(
  { userId: 1, postId: 1 },
  {
    unique: true,
    partialFilterExpression: {
      target: PostShareTarget.PROFILE,
      isDeleted: false,
      deletedAt: null,
    },
  },
);
