/**
 * Pricing Tax Model
 * Defines tax rates that can be applied to subscription pricing
 * based on country/region and billing cycle.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IPricingTax extends Document {
  name: string;
  code: string;
  rate: number;
  country?: string;
  region?: string;
  isInclusive: boolean;
  applicableBillingCycles: string[];
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const PricingTaxSchema = new Schema<IPricingTax>({
  name: {
    type: String,
    required: [true, 'Tax name is required'],
    trim: true,
    maxlength: [100, 'Tax name cannot exceed 100 characters'],
  },
  code: {
    type: String,
    required: [true, 'Tax code is required'],
    unique: true,
    trim: true,
    uppercase: true,
    match: [/^[A-Z0-9_]+$/, 'Tax code must contain only uppercase letters, numbers, and underscores'],
  },
  rate: {
    type: Number,
    required: [true, 'Tax rate is required'],
    min: [0, 'Tax rate cannot be negative'],
    max: [100, 'Tax rate cannot exceed 100%'],
  },
  country: {
    type: String,
    trim: true,
    uppercase: true,
    maxlength: [2, 'Country code must be 2 characters (ISO 3166-1 alpha-2)'],
    default: null,
  },
  region: {
    type: String,
    trim: true,
    maxlength: [50, 'Region cannot exceed 50 characters'],
    default: null,
  },
  isInclusive: {
    type: Boolean,
    default: false,
  },
  applicableBillingCycles: [{
    type: String,
    enum: ['monthly', 'quarterly', 'half_yearly', 'yearly', 'lifetime'],
  }],
  isActive: {
    type: Boolean,
    default: true,
  },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true },
});

PricingTaxSchema.index({ code: 1 }, { unique: true });
PricingTaxSchema.index({ isActive: 1 });
PricingTaxSchema.index({ country: 1, region: 1 });

export const PricingTax = mongoose.models.PricingTax || mongoose.model<IPricingTax>('PricingTax', PricingTaxSchema);