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

export type HostDocument = HydratedDocument<Host>

// A bookable user. One Host per workspace user who exposes public booking pages.
// A User becomes a Host only when made bookable (so most users never get a row).
// `email` matches the Stalwart account; `stalwartAccountId` is the management
// account id (x:Account) used to provision the calendar credential and resolve
// the calendar principal. Kept as a distinct collection from User so scheduling
// stays extractable to a microservice later (see CLAUDE.md §"Hosting").
@Schema({ collection: 'scheduling_hosts', timestamps: true })
export class Host {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

  // OIDC subject (Authentik `sub`) of the underlying workspace user.
  @Prop({ required: true, index: true })
  authentikUserId!: string

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

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

  // URL segment in the public booking page: booking.dezky.eu/:tenantSlug/:slug/...
  @Prop({ required: true, lowercase: true, trim: true })
  slug!: string

  // IANA tz the host's availability is authored/displayed in, e.g. "Europe/Copenhagen".
  @Prop({ required: true })
  timezone!: string

  // Stalwart management account id (x:Account) — used for on-behalf credential
  // provisioning and to locate the calendar principal.
  @Prop({ required: true })
  stalwartAccountId!: string

  // Calendar the confirmed bookings are written to.
  @Prop()
  defaultCalendarId?: string

  // Calendars consulted for free/busy. Defaults to [defaultCalendarId] at read time.
  @Prop({ type: [String], default: [] })
  busyCalendarIds!: string[]

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

export const HostSchema = SchemaFactory.createForClass(Host)
// Public URL uniqueness + fast lookup; one Host row per workspace user.
HostSchema.index({ tenantId: 1, slug: 1 }, { unique: true })
HostSchema.index({ tenantId: 1, authentikUserId: 1 }, { unique: true })
