const mongoose = require('mongoose');

const companySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    lowercase: true,
    trim: true
  },
  phone: {
    type: String,
    trim: true
  },
  website: {
    type: String,
    trim: true
  },
  logo: {
    type: String // URL or path to logo file
  },
  address: {
    street: String,
    city: String,
    state: String,
    zipCode: String,
    country: String
  },
publicPortalEnabled: Boolean,
  publicPortalTemplate: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Template' 
  },
  publicPortalSlug: { 
    type: String, 
    sparse: true 
  },
bankAccounts: [{
  nibOrIban:        { type: String, trim: true },
  accountNumber:    { type: String, trim: true },
  accountHolder:    { type: String, trim: true },
  bankName:         { type: String, trim: true },
  isPrimary:        { type: Boolean, default: false },     // opcional: conta principal
  createdAt:        { type: Date, default: Date.now }
}],
mobileWallets: {
  mpesa: { type: String, trim: true },
  emola: { type: String, trim: true },
  mkesh: { type: String, trim: true },
},
// Add to companySchema
publicPortal: {
  enabled: { type: Boolean, default: false },
  slug: { 
    type: String, 
    sparse: true,
    trim: true,
    lowercase: true,
    match: /^[a-z0-9]+(?:-[a-z0-9]+)*$/
  },
  variant: { 
    type: String, 
    default: 'default',
    enum: ['default', 'minimal', 'modern']
  },
  publishedAt: { type: Date },
  publishedBy: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User' 
  }
},
  taxId: {
    type: String,
    trim: true
  },
  vatNumber: {
    type: String,
    trim: true
  },
  currency: {
    type: String,
    default: 'USD',
    enum: ['USD', 'EUR', 'GBP', 'CAD', 'MT', 'JPY', 'CHF', 'CNY']
  },
  taxRate: {
    type: Number,
    default: 0,
    min: 0,
    max: 100
  },
  paymentTerms: {
    type: String,
    default: 'Net 30'
  },
  invoiceNumberPrefix: {
    type: String,
    default: 'INV-',
    trim: true
  },
  quotationNumberPrefix: {
    type: String,
    default: 'QUO-',
    trim: true
  },
  worksheetNumberPrefix: {
    type: String,
    default: 'WS-',
    trim: true
  },
  purchaseOrderNumberPrefix: {
    type: String,
    default: 'PO-',
    trim: true
  },
  nextInvoiceNumber: {
    type: Number,
    default: 1
  },
  nextQuotationNumber: {
    type: Number,
    default: 1
  },
  nextWorksheetNumber: {
    type: Number,
    default: 1
  },
  nextPurchaseOrderNumber: {
    type: Number,
    default: 1
  }
}, {
  timestamps: true
});

companySchema.index({ "publicPortal.slug": 1 }, { unique: true, sparse: true });
module.exports = mongoose.model('Company', companySchema);