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

export type PriceDocument = HydratedDocument<Price>

export type PriceCycle = 'monthly' | 'quarterly' | 'yearly'
export type PriceCurrency = 'DKK' | 'EUR' | 'USD'
export type PricePlan = 'mvp' | 'pro' | 'enterprise'

// One row per (plan, cycle). Each row holds an independent per-currency
// amount map so operators can set clean round numbers in every currency
// (49 DKK / 7 EUR / 7 USD) instead of FX-derived fractions. Currency without
// a value means "we don't sell this plan/cycle in that currency"; the wizard
// rejects provisioning if a chosen currency isn't priced.
//
// All amounts in MINOR units (øre / cents / cents). 4900 = 49.00, regardless
// of currency.
@Schema({ collection: 'prices', timestamps: true })
export class Price {
  @Prop({ enum: ['mvp', 'pro', 'enterprise'], required: true, index: true })
  plan!: PricePlan

  @Prop({ enum: ['monthly', 'quarterly', 'yearly'], required: true, index: true })
  cycle!: PriceCycle

  @Prop({
    type: {
      DKK: { type: Number, min: 0 },
      EUR: { type: Number, min: 0 },
      USD: { type: Number, min: 0 },
    },
    required: true,
    default: () => ({}),
  })
  amounts!: {
    DKK?: number
    EUR?: number
    USD?: number
  }

  // Per-currency Stripe Price IDs, mapping this catalog row to Stripe. Seeded
  // when Stripe billing is enabled; absent in dev (derived billing).
  @Prop({
    type: {
      DKK: { type: String },
      EUR: { type: String },
      USD: { type: String },
    },
    default: () => ({}),
  })
  stripePriceIds?: {
    DKK?: string
    EUR?: string
    USD?: string
  }

  // Soft-active flag. When the operator changes a row's amounts we mutate
  // the row in place; deactivation is for cases like end-of-life'd plans
  // where we want to preserve subs' priceId references without making the
  // row attach to NEW provisioning runs.
  @Prop({ type: Boolean, default: true, index: true })
  active!: boolean
}

export const PriceSchema = SchemaFactory.createForClass(Price)
// One active row per (plan, cycle). Partial filter keeps deactivated history
// rows from blocking the index.
PriceSchema.index(
  { plan: 1, cycle: 1 },
  { unique: true, partialFilterExpression: { active: true } },
)
