/**
 * companySites
 *
 * Types and helpers for ConnectWise company sites (addresses).
 */

import { connectWiseApi } from "../../../constants";

export interface CWCompanySite {
  id: number;
  name: string;
  addressLine1?: string | null;
  addressLine2?: string | null;
  city?: string | null;
  stateReference?: { id: number; identifier: string; name: string } | null;
  zip?: string | null;
  country?: { id: number; name: string } | null;
  phoneNumber?: string | null;
  faxNumber?: string | null;
  taxCodeId?: number | null;
  expenseReimbursement?: number | null;
  primaryAddressFlag?: boolean;
  defaultShippingFlag?: boolean;
  defaultBillingFlag?: boolean;
  defaultMailingFlag?: boolean;
  mobileGuid?: string | null;
  calendar?: any | null;
  timeZone?: any | null;
  company?: { id: number; identifier: string; name: string } | null;
  _info?: Record<string, any>;
}

export interface SerializedCwSite {
  id: number;
  name: string;
  address: {
    line1: string | null;
    line2: string | null;
    city: string | null;
    state: string | null;
    zip: string | null;
    country: string;
  };
  phoneNumber: string | null;
  faxNumber: string | null;
  primaryAddressFlag: boolean;
  defaultShippingFlag: boolean;
  defaultBillingFlag: boolean;
  defaultMailingFlag: boolean;
}

/**
 * Serialize a raw ConnectWise company site into a clean API shape.
 */
export function serializeCwSite(site: CWCompanySite): SerializedCwSite {
  return {
    id: site.id,
    name: site.name,
    address: {
      line1: site.addressLine1 ?? null,
      line2: site.addressLine2 ?? null,
      city: site.city ?? null,
      state: site.stateReference?.name ?? null,
      zip: site.zip ?? null,
      country: site.country?.name ?? "United States",
    },
    phoneNumber: site.phoneNumber || null,
    faxNumber: site.faxNumber || null,
    primaryAddressFlag: site.primaryAddressFlag ?? false,
    defaultShippingFlag: site.defaultShippingFlag ?? false,
    defaultBillingFlag: site.defaultBillingFlag ?? false,
    defaultMailingFlag: site.defaultMailingFlag ?? false,
  };
}

/**
 * Fetch all sites for a given CW company ID.
 */
export async function fetchCompanySites(
  cwCompanyId: number
): Promise<CWCompanySite[]> {
  const response = await connectWiseApi.get<CWCompanySite[]>(
    `/company/companies/${cwCompanyId}/sites?pageSize=1000`
  );
  return response.data ?? [];
}

/**
 * Fetch a single site by CW company ID and site ID.
 */
export async function fetchCompanySite(
  cwCompanyId: number,
  siteId: number
): Promise<CWCompanySite | null> {
  try {
    const response = await connectWiseApi.get<CWCompanySite>(
      `/company/companies/${cwCompanyId}/sites/${siteId}`
    );
    return response.data ?? null;
  } catch {
    return null;
  }
}
