/*
docker run -v ./script.js:/app/script.js --rm playwright:1.47.0
*/
import type { Page } from "playwright";
import forms from "../forms.ts";

export type CompanyInfo = {
  raisonSociale: string;
  adresse: string;
  codePostal: string;
  ville: string;
  pays: string; // France (FR)
  telephoneFixe?: string;
  telephonePortable?: string;
  email: string;
  siteWeb: string;
  logoFilePath: string;
};

export type CompanyID = {
  directeurs: string; // Nom du(des) gestionnaire(s) (PDG, directeur, président...)
  responsableRGPD: string; // Délégué à la protection des données (DPO, contact RGPD, ...)
  capital: string; // Capital
  formeJuridique: string; // Type d'entité légale (SASU,...)
  siren: string; // SIREN
  siret: string; // SIRET
  naf_ape: string; // NAF-APE
  rcs_rm: string; // RCS/RM (RNE)
  numEori?: string; // numéro EORI (douanes)
  numRna?: string; // numéro RNA (associations)
  numTva: string; // Numéro de TVA
  objetDeLaSociete: string; // Objet de la société
  moisDebutExercice: string; // Mois de début d'exercice
};

export type Company = {
  info: CompanyInfo;
  ID: CompanyID;
};

const companyInfoDolibarrInputNames = new Map(Object.entries({
  raisonSociale: "name",
  adresse: "MAIN_INFO_SOCIETE_ADDRESS",
  codePostal: "MAIN_INFO_SOCIETE_ZIP",
  ville: "MAIN_INFO_SOCIETE_TOWN",
  pays: "country_id:select",
  telephoneFixe: "phone",
  telephonePortable: "phone_mobile",
  email: "mail",
  siteWeb: "web",
  logoFilePath: "logo_squarred:file",
})) as Map<keyof CompanyInfo, string>;

const companyIDDolibarrInputNames = new Map(Object.entries({
  directeurs: "MAIN_INFO_SOCIETE_MANAGERS",
  responsableRGPD: "MAIN_INFO_GDPR",
  capital: "capital",
  formeJuridique: "forme_juridique_code:select",
  siren: "siren",
  siret: "siret",
  naf_ape: "ape",
  rcs_rm: "rcs",
  numEori: "MAIN_INFO_PROFID5",
  numRna: "MAIN_INFO_PROFID6",
  numTva: "tva",
  objetDeLaSociete: "socialobject",
  moisDebutExercice: "SOCIETE_FISCAL_MONTH_START:select",
})) as Map<keyof CompanyID, string>;

async function setupCompany(
  { imgFolderPath, page, dolibarrAddress }: {
    imgFolderPath: string;
    page: Page;
    dolibarrAddress: string;
  },
  company: Company,
): Promise<void> {
  await page.goto(`${dolibarrAddress}/admin/company.php`);

  await forms.fillForm(
    { page, imgFolderPath },
    company.info,
    companyInfoDolibarrInputNames,
    1,
  );

  await forms.fillForm(
    { page, imgFolderPath },
    company.ID,
    companyIDDolibarrInputNames,
    2,
  );
}

export default {
  setupCompany,
};
