import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { resolveManagedFileUrls } from '../../../common/utils/public-url.util';
import { User } from '../../users/schemas/user.schema';
import { MarketplaceListingCategory } from '../enums/marketplace-listing-category.enum';
import { MarketplaceListingCondition } from '../enums/marketplace-listing-condition.enum';

export type InstrumentDocument = HydratedDocument<Instrument>;

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

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

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

  @Prop({ required: true, min: 0 })
  price!: number;

  @Prop({ default: 'SAR', trim: true, maxlength: 8, uppercase: true })
  currency!: string;

  @Prop({ required: true, min: 0, default: 1 })
  quantity!: number;

  @Prop({ type: [String], default: [] })
  imageUrls!: string[];

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

  @Prop({
    type: String,
    enum: MarketplaceListingCondition,
    default: MarketplaceListingCondition.USED,
    index: true,
  })
  condition!: MarketplaceListingCondition;

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

  @Prop({
    type: String,
    enum: MarketplaceListingCategory,
    default: MarketplaceListingCategory.MUSICAL_INSTRUMENT,
    index: true,
  })
  listingCategory!: MarketplaceListingCategory;
}

export const InstrumentSchema = SchemaFactory.createForClass(Instrument);
InstrumentSchema.index({ ownerAdminId: 1, createdAt: -1 });
InstrumentSchema.index({ isActive: 1, createdAt: -1 });
InstrumentSchema.index({ title: 1, isActive: 1, createdAt: -1 });
InstrumentSchema.index({ listingCategory: 1, isActive: 1, createdAt: -1 });
InstrumentSchema.index({ condition: 1, isActive: 1, createdAt: -1 });
InstrumentSchema.index({ instrumentType: 1, isActive: 1, createdAt: -1 });

const transformManagedInstrumentFiles = (_doc: unknown, ret: any) => {
  ret.imageUrls = resolveManagedFileUrls(ret.imageUrls);
  return ret;
};

InstrumentSchema.set('toJSON', { transform: transformManagedInstrumentFiles });
InstrumentSchema.set('toObject', { transform: transformManagedInstrumentFiles });
