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

export type AvailabilityScheduleDocument = HydratedDocument<AvailabilitySchedule>

// An interval within a day, in MINUTES from local midnight in the schedule's tz.
// e.g. 09:00–17:00 => { startMinute: 540, endMinute: 1020 }.
export interface MinuteInterval {
  startMinute: number
  endMinute: number
}

export interface WeeklyRule {
  dayOfWeek: number // 0=Sun .. 6=Sat
  intervals: MinuteInterval[]
}

export interface DateOverride {
  date: string // "YYYY-MM-DD" in the schedule tz
  isUnavailable: boolean // true => whole day blocked (intervals ignored)
  intervals: MinuteInterval[] // replace the weekly intervals for this date
}

// Recurring weekly availability + specific-date overrides, authored in `timezone`.
// Slot computation converts these local windows to UTC via Luxon (DST-correct).
@Schema({ collection: 'scheduling_availability_schedules', timestamps: true })
export class AvailabilitySchedule {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

  @Prop({ type: Types.ObjectId, ref: 'Host', required: true, index: true })
  hostId!: Types.ObjectId

  @Prop({ required: true, trim: true })
  name!: string

  @Prop({ required: true })
  timezone!: string

  @Prop({
    type: [
      {
        dayOfWeek: { type: Number, min: 0, max: 6, required: true },
        intervals: [{ startMinute: Number, endMinute: Number }],
      },
    ],
    default: [],
  })
  weeklyRules!: WeeklyRule[]

  @Prop({
    type: [
      {
        date: { type: String, required: true },
        isUnavailable: { type: Boolean, default: false },
        intervals: [{ startMinute: Number, endMinute: Number }],
      },
    ],
    default: [],
  })
  dateOverrides!: DateOverride[]
}

export const AvailabilityScheduleSchema = SchemaFactory.createForClass(AvailabilitySchedule)
