import { api as apiClient } from "@/auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";
import type {
  Company,
  CompanyListFilter,
  CompanyProfile,
  CompanyStats,
  CustomerBooking,
  CustomerDocument,
  CustomerPayment,
  PaginatedCompanies,
  ProfileStatus,
} from "@/types/customer";

const cleanParams = (params: object) =>
  Object.fromEntries(
    Object.entries(params).filter(
      ([, value]) => value !== undefined && value !== "" && value !== null,
    ),
  );

/** Lift attributes JSONB into the flat contact/manager fields the UI reads. */
function mapCompany(dto: Record<string, unknown>): Company {
  const attrs = (dto.attributes as Record<string, unknown> | null) ?? {};
  return {
    ...(dto as unknown as Company),
    companyProfiles: (dto.companyProfiles as Company["companyProfiles"]) ?? [],
    contactPersonName: (attrs.contactPersonName as string | null) ?? null,
    contactPersonPhone: (attrs.contactPersonPhone as string | null) ?? null,
    generalManagerName: (attrs.generalManagerName as string | null) ?? null,
    generalManagerEmail: (attrs.generalManagerEmail as string | null) ?? null,
    generalManagerPhone: (attrs.generalManagerPhone as string | null) ?? null,
  };
}

export const customersService = {
  stats(): Promise<CompanyStats> {
    return apiClient
      .get<CompanyStats>(URL_CONSTANTS.COMPANIES.STATS)
      .then((r) => r.data);
  },

  list(filter: CompanyListFilter): Promise<PaginatedCompanies> {
    return apiClient
      .get<{ items: Record<string, unknown>[]; total: number }>(
        URL_CONSTANTS.COMPANIES.BASE,
        { params: cleanParams(filter) },
      )
      .then((r) => ({
        items: r.data.items.map(mapCompany),
        total: r.data.total,
      }));
  },

  getById(id: string): Promise<Company | undefined> {
    return apiClient
      .get<Record<string, unknown>>(URL_CONSTANTS.COMPANIES.BY_ID(id))
      .then((r) => mapCompany(r.data));
  },

  bookingsFor(companyId: string): Promise<CustomerBooking[]> {
    return apiClient
      .get<CustomerBooking[]>(
        URL_CONSTANTS.COMPANIES.BOOKINGS_CUSTOMER_VIEW(companyId),
      )
      .then((r) => r.data);
  },

  documentsFor(companyId: string): Promise<CustomerDocument[]> {
    return apiClient
      .get<CustomerDocument[]>(URL_CONSTANTS.COMPANIES.DOCUMENTS(companyId))
      .then((r) => r.data);
  },

  paymentsFor(companyId: string): Promise<CustomerPayment[]> {
    return apiClient
      .get<CustomerPayment[]>(
        URL_CONSTANTS.COMPANIES.PAYMENTS_CUSTOMER_VIEW(companyId),
      )
      .then((r) => r.data);
  },

  setProfileStatus(profileId: string, status: ProfileStatus): Promise<CompanyProfile> {
    return apiClient
      .patch<CompanyProfile>(
        URL_CONSTANTS.COMPANIES.PROFILE_STATUS(profileId),
        { status },
      )
      .then((r) => r.data);
  },

  /** Approve / change a company's status (e.g. pending → active). */
  setCompanyStatus(companyId: string, status: string): Promise<unknown> {
    return apiClient
      .patch(URL_CONSTANTS.COMPANIES.BY_ID(companyId), { status })
      .then((r) => r.data);
  },
};
