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';

export type RepairShopDocument = HydratedDocument<RepairShop>;

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

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

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

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

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

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

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

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

  @Prop({ type: Number, min: -90, max: 90, default: null })
  latitude!: number | null;

  @Prop({ type: Number, min: -180, max: 180, default: null })
  longitude!: number | null;

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

export const RepairShopSchema = SchemaFactory.createForClass(RepairShop);
RepairShopSchema.index({ ownerAdminId: 1, createdAt: -1 });
RepairShopSchema.index({ isActive: 1, createdAt: -1 });
RepairShopSchema.index({ name: 1, isActive: 1, createdAt: -1 });

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

RepairShopSchema.set('toJSON', { transform: transformManagedRepairShopFiles });
RepairShopSchema.set('toObject', { transform: transformManagedRepairShopFiles });
