/**
 * AD_OrgInfo write payload shared by `admin/organizations/store.post.ts` (after the AD_Org create)
 * and `admin/organizations/[id]/organization-info/index.put.ts`.
 *
 * AD_OrgInfo is a 1:1 row keyed by AD_Org_ID that iDempiere creates together with the org, so it is
 * always written with `PUT models/ad_orginfo/{AD_Org_ID}`. Only keys present in `body` are written
 * (changed-field semantics like the partner update); `''` on a reference clears it (`0`).
 *
 * Logo: `logoData` (base64, no data-URL prefix) creates a new AD_Image through the nested image object
 * (same contract as `AD_Image_ID` on AD_User); `removeLogo: true` clears `Logo_ID`.
 */
export const buildOrgInfoPayload = (body: any, opts: { orgName?: string } = {}) => {
  const payload: any = {}
  const has = (k: string) => Object.prototype.hasOwnProperty.call(body ?? {}, k)

  const addIfPresent = (bodyKey: string, apiKey: string, map?: (v: any) => any) => {
    if (!has(bodyKey)) return
    const v = body[bodyKey]
    payload[apiKey] = map ? map(v) : (v ?? '')
  }
  const addRef = (bodyKey: string, apiKey: string, tableName: string) => {
    if (!has(bodyKey)) return
    const v = body[bodyKey]
    if (v === '' || v === null || v === undefined || Number(v) === 0) {
      payload[apiKey] = 0
    } else {
      payload[apiKey] = { id: Number(v), tableName }
    }
  }

  // Mandatory in iDempiere (DUNS, TaxID, ReceiptFooterMsg) → keep the legacy '?' placeholder when emptied
  addIfPresent('DUNS', 'DUNS', (v) => String(v ?? '').trim() || '?')
  addIfPresent('taxID', 'taxID', (v) => String(v ?? '').trim() || '?')
  addIfPresent('receiptFooterMsg', 'receiptFooterMsg', (v) => String(v ?? '').trim() || '1')
  addIfPresent('subtitle', 'lY_Subtitle')
  addIfPresent('phone', 'phone')
  addIfPresent('phone2', 'phone2')
  addIfPresent('fax', 'fax')
  addIfPresent('eMail', 'eMail')
  addIfPresent('timeZone', 'timeZone')

  addRef('locationId', 'C_Location_ID', 'C_Location')
  addRef('warehouseId', 'M_Warehouse_ID', 'M_Warehouse')
  addRef('dropShipWarehouseId', 'DropShip_Warehouse_ID', 'M_Warehouse')
  addRef('orgTypeId', 'AD_OrgType_ID', 'AD_OrgType')
  addRef('supervisorId', 'Supervisor_ID', 'AD_User')
  addRef('parentOrgId', 'Parent_Org_ID', 'AD_Org')
  addRef('calendarId', 'C_Calendar_ID', 'C_Calendar')
  addRef('transferBankId', 'TransferBank_ID', 'C_Bank')
  addRef('transferCashBookId', 'TransferCashBook_ID', 'C_CashBook')

  if (body?.removeLogo === true) {
    payload.Logo_ID = 0
  } else if (typeof body?.logoData === 'string' && body.logoData.trim() !== '') {
    const data = body.logoData.includes(',') ? body.logoData.split(',').pop() : body.logoData
    const img: any = { data: String(data).trim(), tableName: 'AD_Image' }
    const name = String(opts.orgName || body?.companyname || body?.name || '').trim()
    if (name) img.name = ('Logo ' + name).slice(0, 60)
    payload.Logo_ID = img
  }

  return payload
}

export const hasOrgInfoKeys = (body: any) => Object.keys(buildOrgInfoPayload(body)).length > 0
