/**
 * EmailContact Model
 *
 * Syncs contacts from Brevo lists to local database for tracking.
 * Maintains contact status and sync history.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type ContactStatus = 'active' | 'inactive' | 'bounced' | 'unsubscribed';

export interface IEmailContact extends Document {
  companyId: string;

  // Brevo contact reference
  brevoContactId?: number;
  email: string;

  // Contact attributes (name, company, etc.)
  attributes?: Record<string, any>;

  // List membership
  listIds?: number[];

  // Status
  status: ContactStatus;
  blacklisted: boolean;

  // Sync tracking
  lastSyncedAt?: Date;

  // Timestamps
  createdAt: Date;
  updatedAt: Date;
}

const EmailContactSchema = new Schema<IEmailContact>(
  {
    companyId: {
      type: String,
      required: true,
      index: true,
    },
    brevoContactId: {
      type: Number,
      index: true,
    },
    email: {
      type: String,
      required: true,
      index: true,
      lowercase: true,
      trim: true,
    },
    attributes: {
      type: Schema.Types.Mixed,
    },
    listIds: [{ type: Number }],
    status: {
      type: String,
      enum: ['active', 'inactive', 'bounced', 'unsubscribed'],
      default: 'active',
    },
    blacklisted: {
      type: Boolean,
      default: false,
    },
    lastSyncedAt: Date,
  },
  { timestamps: true }
);

// Compound unique index for company + email
EmailContactSchema.index({ companyId: 1, email: 1 }, { unique: true });

export const EmailContact = mongoose.model<IEmailContact>(
  'EmailContact',
  EmailContactSchema
);