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

export type TenantSsoAppDocument = HydratedDocument<TenantSsoApp>

// An external application the tenant has registered to use Dezky (Authentik) as
// its identity provider. We mirror the Authentik objects here (provider +
// application refs) so the portal can list/manage without re-querying Authentik;
// the client_secret is never stored — it's shown once at creation time.
@Schema({ collection: 'tenant_sso_apps', timestamps: true })
export class TenantSsoApp {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

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

  // 'oidc' for now (SAML support can join later without a schema change).
  @Prop({ enum: ['oidc', 'saml'], default: 'oidc' })
  protocol!: 'oidc' | 'saml'

  // OIDC client id (safe to display). Secret is intentionally not persisted.
  @Prop()
  clientId?: string

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

  // Authentik handles — used for delete/reconcile.
  @Prop()
  authentikAppSlug?: string

  @Prop()
  authentikAppPk?: string // application uuid

  @Prop({ type: Number })
  authentikProviderPk?: number
}

export const TenantSsoAppSchema = SchemaFactory.createForClass(TenantSsoApp)
