import mongoose, { Schema, Document } from 'mongoose';
// Import Company to ensure it's registered before Project uses it in populate
import './Company';

export interface IProjectDocument extends Document {
  _id: any;
  companyId: any;
  segment?: 'residential' | 'commercial';
  name: string;
  code: string;
  location: {
    address: string;
    coordinates: { lat: number; lng: number };
  };
  capacityMWp: number;
  commissioningDate: Date;
  status: 'planning' | 'construction' | 'operational' | 'decommissioned';
  managerId?: any;
  meteocontrol?: {
    siteKey?: string;
    apiKey?: string;
    systemKey?: string;
    useV2API?: boolean;
  };
  createdAt: Date;
  updatedAt: Date;
}

const projectSchema = new Schema<IProjectDocument>(
  {
    _id: { type: Schema.Types.Mixed, default: () => new mongoose.Types.ObjectId().toString() }, // Support both string demo IDs and auto-gen string IDs
    companyId: { type: Schema.Types.Mixed, ref: 'Company', required: true },
    segment: {
      type: String,
      enum: ['residential', 'commercial'],
      default: 'commercial',
    },
    name: { type: String, required: true },
    code: { type: String, required: true },
    location: {
      address: { type: String, required: true },
      coordinates: {
        lat: { type: Number, required: true },
        lng: { type: Number, required: true },
      },
    },
    capacityMWp: { type: Number, required: true },
    commissioningDate: { type: Date, required: true },
    status: {
      type: String,
      enum: ['planning', 'construction', 'operational', 'decommissioned'],
      default: 'planning',
    },
    managerId: { type: Schema.Types.Mixed, ref: 'User' },
    meteocontrol: {
      siteKey: { type: String, default: '' },
      apiKey: { type: String, default: '' },
      systemKey: { type: String, default: '' },
      useV2API: { type: Boolean, default: false },
    },
  },
  {
    timestamps: true,
  }
);

projectSchema.index({ companyId: 1 });
projectSchema.index({ code: 1 });
projectSchema.index({ status: 1 });

export const Project = mongoose.model<IProjectDocument>('Project', projectSchema);
