import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document, Types } from 'mongoose'

export type ShareRecordDocument = ShareRecord & Document
export type ShareVisitDocument = ShareVisit & Document

@Schema({ timestamps: true })
export class ShareRecord {
  @Prop({ type: Types.ObjectId, ref: 'User', required: true })
  userId: Types.ObjectId

  @Prop({ required: true, unique: true })
  shareCode: string

  @Prop({ default: 'app' })
  type: string

  @Prop({ default: '' })
  refId: string

  @Prop({ default: '' })
  title: string

  @Prop({ default: '' })
  description: string

  @Prop({ default: 'link' })
  channel: string

  @Prop({ default: 0 })
  visitCount: number

  @Prop({ default: 0 })
  creditedCount: number

  @Prop({ default: true })
  isActive: boolean

  readonly createdAt?: Date
  readonly updatedAt?: Date
}

@Schema({ timestamps: true })
export class ShareVisit {
  @Prop({ type: Types.ObjectId, ref: 'ShareRecord', required: true })
  shareId: Types.ObjectId

  @Prop({ type: Types.ObjectId, ref: 'User', required: true })
  sharerId: Types.ObjectId

  @Prop({ required: true })
  visitorId: string

  @Prop({ type: Types.ObjectId, ref: 'User' })
  visitorUserId: Types.ObjectId

  @Prop({ default: false })
  credited: boolean

  @Prop()
  creditedAt?: Date

  readonly createdAt?: Date
  readonly updatedAt?: Date
}

export const ShareRecordSchema = SchemaFactory.createForClass(ShareRecord)
export const ShareVisitSchema = SchemaFactory.createForClass(ShareVisit)

ShareRecordSchema.index({ userId: 1, createdAt: -1 })
ShareVisitSchema.index({ shareId: 1, visitorId: 1 }, { unique: true })
ShareVisitSchema.index({ sharerId: 1, createdAt: -1 })
