/**
 * Product & Product Category Models
 */

import mongoose, { Schema, Document } from 'mongoose';

export type ProductStatus = 'active' | 'draft' | 'discontinued';
export type AudienceType = 'b2b' | 'b2c' | 'both';

/**
 * How a product is sold, which decides the pricing fields that apply.
 *
 * 'direct' is the historical behaviour (a one-time `price` + `currency`) and is
 * the default, so every product created before this field existed reads back as
 * Direct Selling with its original pricing intact — no migration required.
 */
export type ProductPricingModel = 'direct' | 'saas';
export type ProductBillingCycle = 'monthly' | 'quarterly' | 'half_yearly' | 'yearly';

export interface IProductCategory extends Document {
  name: string;
  companyId: string;
  description?: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface IProduct extends Document {
  name: string;
  companyId: string;
  categoryId?: string;
  /** Defaults to 'direct'; absent on products created before pricing models. */
  pricingModel?: ProductPricingModel;
  // ── Direct Selling ──────────────────────────────────────────────────────
  /** One-time purchase price. Pre-existing field, unchanged. */
  price?: number;
  currency?: string;
  discountPercent?: number;
  taxPercent?: number;
  sku?: string;
  // ── SaaS / subscription ─────────────────────────────────────────────────
  monthlyPrice?: number;
  yearlyPrice?: number;
  billingCycle?: ProductBillingCycle;
  trialAvailable?: boolean;
  trialDurationDays?: number;
  setupFee?: number;
  autoRenewal?: boolean;
  cancellationPeriodDays?: number;
  status: ProductStatus;
  audienceType: AudienceType;
  usp?: string;
  description?: string;
  features?: string[];
  icpIds: string[];
  personaIds: string[];
  marketingCopy?: string;
  // Media & Resources
  images?: string[];           // Array of image URLs
  catalogPdfUrl?: string;      // PDF catalog URL
  videoUrls?: string[];        // YouTube video URLs
  designUrl?: string;           // Canva/Figma design link
  createdBy?: string;          // User ID who created this record
  createdAt: Date;
  updatedAt: Date;
}

const ProductCategorySchema = new Schema<IProductCategory>({
  name: {
    type: String,
    required: [true, 'Category name is required'],
    trim: true,
    minlength: [2, 'Category name must be at least 2 characters long'],
    maxlength: [100, 'Category name cannot exceed 100 characters'],
    validate: {
      validator: (v: string) => /^[a-zA-Z0-9\s&\-]+$/.test(v),
      message: 'Category name can only contain letters, numbers, spaces, & and -',
    },
  },
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  description: String
}, {
  timestamps: true
});

ProductCategorySchema.index({ companyId: 1 });
// Unique compound index: one category name per company (case-insensitive handled at route level)
ProductCategorySchema.index({ companyId: 1, name: 1 }, { unique: true });

const ProductSchema = new Schema<IProduct>({
  name: {
    type: String,
    required: [true, 'Product name is required'],
    trim: true,
    maxlength: [200, 'Product name cannot exceed 200 characters']
  },
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  categoryId: {
    type: String,
    index: true
  },
  price: {
    type: Number,
    min: [0.01, 'Price must be a positive value'],
    validate: {
      validator: (v: number) => v == null || v > 0,
      message: 'Price must be a positive value'
    }
  },
  currency: {
    type: String,
    enum: ['INR', 'USD', 'EUR', 'GBP', 'AED'],
    default: 'INR'
  },
  // ── Pricing model ────────────────────────────────────────────────────────
  // Every field below is optional with no required validator, so existing
  // documents continue to load and save unchanged. `currency` above is shared
  // by both models rather than duplicated as a separate subscription currency.
  pricingModel: {
    type: String,
    enum: ['direct', 'saas'],
    default: 'direct'
  },
  // Direct Selling
  discountPercent: {
    type: Number,
    min: [0, 'Discount cannot be negative'],
    max: [100, 'Discount cannot exceed 100%']
  },
  taxPercent: {
    type: Number,
    min: [0, 'Tax cannot be negative'],
    max: [100, 'Tax cannot exceed 100%']
  },
  sku: { type: String, trim: true, maxlength: [64, 'SKU cannot exceed 64 characters'] },
  // SaaS / subscription
  monthlyPrice: { type: Number, min: [0, 'Monthly price cannot be negative'] },
  yearlyPrice: { type: Number, min: [0, 'Yearly price cannot be negative'] },
  billingCycle: {
    type: String,
    enum: ['monthly', 'quarterly', 'half_yearly', 'yearly'],
    default: 'monthly'
  },
  trialAvailable: { type: Boolean, default: false },
  trialDurationDays: { type: Number, min: [1, 'Trial duration must be at least 1 day'] },
  setupFee: { type: Number, min: [0, 'Setup fee cannot be negative'] },
  autoRenewal: { type: Boolean, default: true },
  cancellationPeriodDays: { type: Number, min: [0, 'Cancellation period cannot be negative'] },
  status: {
    type: String,
    enum: ['active', 'draft', 'discontinued'],
    default: 'draft'
  },
  audienceType: {
    type: String,
    enum: ['b2b', 'b2c', 'both'],
    required: true
  },
  usp: String,
  description: String,
  features: [String],
  icpIds: [String],
  personaIds: [String],
  marketingCopy: String,
  // Media & Resources
  images: [String],           // Array of image URLs
  catalogPdfUrl: String,      // PDF catalog URL
  videoUrls: [String],        // YouTube video URLs
  designUrl: String,           // Canva/Figma design link
  createdBy: String           // User ID who created this record
}, {
  timestamps: true
});

ProductSchema.index({ companyId: 1, categoryId: 1 });
ProductSchema.index({ companyId: 1, status: 1 });

export const ProductCategory = mongoose.model<IProductCategory>('ProductCategory', ProductCategorySchema);
export const Product = mongoose.model<IProduct>('Product', ProductSchema);
