import { client } from "@/utils/api";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { ApiResponse } from "@/types/apiResponse";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import { isAxiosError } from "axios";

export interface ExternalProfileResponse {
  id: string;
  userId: string;
  companyId: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string | null;
  nationalId: string | null;
  jobTitle: string | null;
  isPrimaryContact: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CompanyResponse {
  id: string;
  name: string;
  type: string;
  status: string;
  tin: string;
  vatNumber: string | null;
  businessLicense: string | null;
  fanNumber: string | null;
  country: string;
  address: string | null;
  phone: string | null;
  email: string | null;
  website: string | null;
  attributes: Record<string, any> | null;
  createdAt: string;
  updatedAt: string;
}

export interface CompanyInfoResponse {
  profile: ExternalProfileResponse;
  company: CompanyResponse;
}

export interface CreateCompanyPayload {
  companyType?: string;
  companyName: string;
  companyEmail?: string;
  companyPhone?: string;
  companyLocation?: string;
  companyAddress?: string;
  tin?: string;
  vatNumber?: string;
  fanNumber?: string;
  jobTitle?: string;
  isPrimaryContact?: boolean;
  attributes?: Record<string, any>;
}

export const companiesService = {
  getInfo: async (): Promise<CompanyInfoResponse | null> => {
    try {
      const response = await client.get<ApiResponse<CompanyInfoResponse>>(
        URL_CONSTANTS.COMPANIES_API.GET_INFO,
      );
      return unwrap(response.data);
    } catch (e) {
      if (isAxiosError(e) && e.response?.status === 404) {
        return null;
      }
      throw e;
    }
  },

  create: async (payload: CreateCompanyPayload): Promise<CompanyInfoResponse> => {
    const response = await client.post<ApiResponse<CompanyInfoResponse>>(
      URL_CONSTANTS.COMPANIES_API.CREATE,
      payload,
    );
    return unwrap(response.data);
  },

  getProfile: async (): Promise<ProfileResponse> => {
    const response = await client.get<ApiResponse<ProfileResponse>>(
      URL_CONSTANTS.COMPANIES_API.PROFILE,
    );
    return unwrap(response.data);
  },

  updateProfile: async (payload: UpdateProfilePayload): Promise<ProfileResponse> => {
    const response = await client.patch<ApiResponse<ProfileResponse>>(
      URL_CONSTANTS.COMPANIES_API.PROFILE,
      payload,
    );
    return unwrap(response.data);
  },

  uploadDocuments: async (
    companyId: string,
    files: Record<string, File | File[] | null>,
  ): Promise<void> => {
    const formData = new FormData();
    for (const [fieldName, fileOrFiles] of Object.entries(files)) {
      if (!fileOrFiles) continue;
      if (Array.isArray(fileOrFiles)) {
        for (const f of fileOrFiles) {
          formData.append(fieldName, f);
        }
      } else {
        formData.append(fieldName, fileOrFiles);
      }
    }
    await client.post(URL_CONSTANTS.COMPANIES_API.DOCUMENTS(companyId), formData);
  },
};
