/**
 * Company Model
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface ICompany extends Document {
  name: string;
  notificationEmail?: string;
  websiteUrl?: string;
  description?: string;
  userIds: string[];
  isActive: boolean;
  subscriptionId?: string;
  subscriptionStatus?: string;
  createdAt: Date;
  updatedAt: Date;
}

const CompanySchema = new Schema<ICompany>({
  name: {
    type: String,
    required: [true, 'Company name is required'],
    trim: true,
    // Mirrors COMPANY_NAME_MAX_LENGTH on the frontend and the register route's
    // isLength check — keep all three in step.
    maxlength: [256, 'Company name cannot exceed 256 characters']
  },
  notificationEmail: {
    type: String,
    trim: true,
    lowercase: true
  },
  websiteUrl: {
    type: String,
    trim: true
  },
  description: {
    type: String,
    trim: true,
    maxlength: [2000, 'Description cannot exceed 2000 characters']
  },
  userIds: [{
    type: String,
    index: true
  }],
  isActive: {
    type: Boolean,
    default: true
  },
  subscriptionId: {
    type: String,
    sparse: true,
  },
  subscriptionStatus: {
    type: String,
    enum: ['trial', 'active', 'expired', 'cancelled', 'pending_payment', 'suspended'],
    sparse: true,
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Indexes
CompanySchema.index({ userIds: 1 });
CompanySchema.index({ isActive: 1 });

export const Company = mongoose.models.Company || mongoose.model<ICompany>('Company', CompanySchema);
