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

export type InvoiceDocument = HydratedDocument<Invoice>

// One customer invoice, synced from Stripe webhooks (invoice.paid /
// payment_failed). `partnerId` is denormalized so the partner billing list is
// one query. Amounts are in minor units. Empty in dev until Stripe is live.
@Schema({ collection: 'invoices', timestamps: true })
export class Invoice {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

  @Prop({ type: Types.ObjectId, ref: 'Partner', index: true, sparse: true })
  partnerId?: Types.ObjectId

  @Prop({ type: Types.ObjectId, ref: 'Subscription', sparse: true })
  subscriptionId?: Types.ObjectId

  // Dedup key for webhook idempotency.
  @Prop({ unique: true, sparse: true, index: true })
  stripeInvoiceId?: string

  @Prop({ trim: true })
  number?: string

  @Prop({ enum: ['DKK', 'EUR', 'USD'], default: 'DKK' })
  currency!: 'DKK' | 'EUR' | 'USD'

  @Prop({ type: Number, default: 0 })
  amountDue!: number

  @Prop({ type: Number, default: 0 })
  amountPaid!: number

  @Prop({
    enum: ['draft', 'open', 'paid', 'void', 'uncollectible', 'past_due'],
    default: 'open',
    index: true,
  })
  status!: 'draft' | 'open' | 'paid' | 'void' | 'uncollectible' | 'past_due'

  @Prop()
  periodStart?: Date

  @Prop()
  periodEnd?: Date

  @Prop()
  hostedInvoiceUrl?: string

  @Prop()
  pdfUrl?: string
}

export const InvoiceSchema = SchemaFactory.createForClass(Invoice)
