import type { IProject } from '../types';

/** Chuẩn hóa _id từ API / BSON (string, ObjectId, { $oid }). */
export function normalizeEntityId(id: unknown): string {
  if (id === null || id === undefined) return '';
  if (typeof id === 'string') return id;
  if (typeof id === 'object' && id !== null && '$oid' in id && typeof (id as { $oid: unknown }).$oid === 'string') {
    return (id as { $oid: string }).$oid;
  }
  if (typeof id === 'object' && id !== null && '_id' in (id as object)) {
    return normalizeEntityId((id as { _id: unknown })._id);
  }
  return String(id);
}

function unwrapRef(ref: unknown): string | undefined {
  if (ref === null || ref === undefined) return undefined;
  if (typeof ref === 'string') return ref;
  if (typeof ref === 'object' && ref !== null && '_id' in ref) {
    const inner = normalizeEntityId((ref as { _id: unknown })._id);
    return inner || undefined;
  }
  const raw = normalizeEntityId(ref);
  return raw || undefined;
}

/**
 * Body cho PUT /projects/:id: chỉ các trường trong schema, tránh spread toàn bộ object
 * (nested ref, field thừa) làm Mongoose / proxy xử lý sai; luôn gửi `segment` rõ ràng.
 */
export function serializeProjectForUpdate(project: IProject): Record<string, unknown> {
  const id = normalizeEntityId(project._id);
  if (!id) throw new Error('Project _id không hợp lệ');

  const companyId = unwrapRef(project.companyId as unknown);
  if (!companyId) throw new Error('companyId không hợp lệ');

  let segment = 'commercial';
  const rawProject = project as any;
  
  // 1. Direct segment check
  if (project.segment === 'residential' || project.segment === 'commercial') {
    segment = project.segment;
  } 
  // 2. Check for alternative field names if segment is missing/invalid
  else {
    const rawVal = rawProject.segment || rawProject.projectType || rawProject.type || rawProject.portfolioType || '';
    const s = String(rawVal).toLowerCase();
    if (s.includes('residential')) {
      segment = 'residential';
    } else if (s.includes('commercial')) {
      segment = 'commercial';
    }
  }

  const payload: Record<string, unknown> = {
    companyId,
    segment,
    name: project.name,
    code: project.code,
    location: project.location,
    capacityMWp: project.capacityMWp,
    commissioningDate: project.commissioningDate,
    status: project.status,
  };

  const managerId = unwrapRef(project.managerId as unknown);
  if (managerId) payload.managerId = managerId;

  if (project.meteocontrol && (project.meteocontrol.siteKey || project.meteocontrol.apiKey || project.meteocontrol.systemKey)) {
    const mc = project.meteocontrol;
    payload.meteocontrol = {
      siteKey: mc.siteKey || '',
      apiKey: mc.apiKey || '',
      systemKey: mc.systemKey || mc.siteKey || '',
      useV2API: mc.useV2API !== false,
    };
  }

  return payload;
}
