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

export type StalwartCredentialDocument = HydratedDocument<StalwartCredential>

export type StalwartCredentialType = 'app_password' | 'oauth'

// Per-host Stalwart credential, encrypted at rest (AES-256-GCM via
// CredentialCipher). One row per host. The secret is an app password minted
// on-behalf through the Stalwart admin JMAP (x:AppPassword/set {accountId}); see
// reference: Phase 0 spike. The plaintext secret is NEVER stored or logged —
// only the ciphertext + iv + authTag triplet.
@Schema({ collection: 'scheduling_stalwart_credentials', timestamps: true })
export class StalwartCredential {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

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

  @Prop({ enum: ['app_password', 'oauth'], default: 'app_password' })
  type!: StalwartCredentialType

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

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

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

  // Stalwart AppPassword object id — kept so we can rotate/destroy it later.
  @Prop()
  appPasswordId?: string

  // JMAP session endpoint (.well-known/jmap) the secret authenticates against.
  @Prop({ required: true })
  jmapSessionUrl!: string

  // CalDAV base URL — retained for the (currently shelved) fallback transport.
  @Prop()
  caldavBaseUrl?: string

  @Prop()
  lastValidatedAt?: Date
}

export const StalwartCredentialSchema = SchemaFactory.createForClass(StalwartCredential)
