/**
 * Shared state shape + API bodies for the Organization pages
 * (`/create/organization`, `/edit/organization-:id`, `/duplicate/organization-:id`).
 *
 * One flat form holds AD_Org + AD_OrgInfo (letterhead, logo, address, warehouse/bank references).
 * - `mapOrganization(org, info)` → form (tolerant PascalCase reads, `Logo_ID.data` = base64)
 * - `organizationBody(form)` / `organizationInfoBody(form)` → request bodies for
 *   `PUT /api/admin/organizations/update` and `PUT /api/admin/organizations/:id/organization-info`
 * - `pickChanged(body, snapshotBody)` → only the keys that differ from the loaded snapshot
 *   (both routes have changed-field semantics; `''` clears a reference)
 * - `saveOrganizationLocation(form)` → C_Location create/update through `/api/settings/locations/*`
 */
export const ORG_TIMEZONE_DEFAULT = 'Europe/Berlin'

export const emptyOrganizationLocation = () => ({
  id: '', address1: '', address2: '', postal: '', city: '',
  countryId: '', country: '', regionId: '', region: ''
})

export const emptyOrganizationForm = (defaults: any = {}) => ({
  id: '', uid: '',
  isActive: true, name: '', value: '', companyname: '', description: '', isSummary: false,
  tenant: '', tenantId: '',
  replicationStrategy: '', replicationStrategyId: '',
  bpartner: '', bpartnerId: '',
  // AD_OrgInfo
  subtitle: '', phone: '', phone2: '', fax: '', eMail: '', receiptFooterMsg: '', taxID: '', DUNS: '',
  timeZone: '',
  logoId: '', logoData: '', removeLogo: false,
  location: emptyOrganizationLocation(),
  warehouse: '', warehouseId: '', dropShipWarehouse: '', dropShipWarehouseId: '',
  orgType: '', orgTypeId: '', supervisor: '', supervisorId: '', parentOrg: '', parentOrgId: '',
  calendar: '', calendarId: '', transferBank: '', transferBankId: '', transferCashBook: '', transferCashBookId: '',
  processing: false,
  alert: { status: '', message: '', processing: false },
  ...defaults
})

const placeholderToEmpty = (v: any) => {
  const s = String(v ?? '').trim()
  return s === '?' || s === '1' || s === '-' ? '' : s
}

export const mapOrganizationLocation = (loc: any) => {
  if (!loc || typeof loc !== 'object') return emptyOrganizationLocation()
  return {
    id: loc?.id || '',
    address1: loc?.Address1 ?? loc?.address1 ?? '',
    address2: loc?.Address2 ?? loc?.address2 ?? '',
    postal: loc?.Postal ?? loc?.postal ?? '',
    city: loc?.City ?? loc?.city ?? '',
    countryId: loc?.C_Country_ID?.id || '',
    country: loc?.C_Country_ID?.identifier || '',
    regionId: loc?.C_Region_ID?.id || '',
    region: loc?.C_Region_ID?.identifier || loc?.RegionName || loc?.regionName || ''
  }
}

export const mapOrganization = (org: any, info: any, opts: { asCopy?: boolean } = {}) => {
  const o = org || {}
  const i = info || {}
  const asCopy = opts.asCopy === true
  const loc = mapOrganizationLocation(i?.C_Location_ID)
  if (asCopy) loc.id = ''
  return emptyOrganizationForm({
    id: asCopy ? '' : (o?.id || ''),
    uid: asCopy ? '' : (o?.uid || ''),
    isActive: o?.IsActive ?? o?.isActive ?? true,
    name: asCopy ? '' : (o?.Name || ''),
    value: asCopy ? '' : (o?.Value || ''),
    companyname: o?.companyname ?? o?.CompanyName ?? '',
    description: o?.Description || '',
    isSummary: o?.IsSummary ?? o?.isSummary ?? false,
    tenant: o?.AD_Client_ID?.identifier || '',
    tenantId: o?.AD_Client_ID?.id || '',
    replicationStrategy: o?.AD_ReplicationStrategy_ID?.identifier || '',
    replicationStrategyId: o?.AD_ReplicationStrategy_ID?.id || '',
    bpartner: asCopy ? '' : (o?.C_BPartner_ID?.identifier || ''),
    bpartnerId: asCopy ? '' : (o?.C_BPartner_ID?.id || ''),
    subtitle: i?.LY_Subtitle ?? i?.lY_Subtitle ?? i?.ly_subtitle ?? '',
    phone: i?.Phone ?? '',
    phone2: i?.Phone2 ?? '',
    fax: i?.Fax ?? '',
    eMail: i?.EMail ?? i?.Email ?? '',
    receiptFooterMsg: placeholderToEmpty(i?.ReceiptFooterMsg),
    taxID: placeholderToEmpty(i?.TaxID),
    DUNS: placeholderToEmpty(i?.DUNS),
    timeZone: i?.TimeZone ?? '',
    logoId: asCopy ? '' : (i?.Logo_ID?.id || ''),
    logoData: i?.Logo_ID?.data || '',
    removeLogo: false,
    location: loc,
    warehouse: i?.M_Warehouse_ID?.identifier || '', warehouseId: i?.M_Warehouse_ID?.id || '',
    dropShipWarehouse: i?.DropShip_Warehouse_ID?.identifier || '', dropShipWarehouseId: i?.DropShip_Warehouse_ID?.id || '',
    orgType: i?.AD_OrgType_ID?.identifier || '', orgTypeId: i?.AD_OrgType_ID?.id || '',
    supervisor: i?.Supervisor_ID?.identifier || '', supervisorId: i?.Supervisor_ID?.id || '',
    parentOrg: i?.Parent_Org_ID?.identifier || '', parentOrgId: i?.Parent_Org_ID?.id || '',
    calendar: i?.C_Calendar_ID?.identifier || '', calendarId: i?.C_Calendar_ID?.id || '',
    transferBank: i?.TransferBank_ID?.identifier || '', transferBankId: i?.TransferBank_ID?.id || '',
    transferCashBook: i?.TransferCashBook_ID?.identifier || '', transferCashBookId: i?.TransferCashBook_ID?.id || ''
  })
}

/** AD_Org part → `/api/admin/organizations/{store|update}` */
export const organizationBody = (form: any) => ({
  isActive: form.isActive ?? true,
  name: form.name ?? '',
  description: form.description ?? '',
  value: form.value ?? '',
  isSummary: form.isSummary ?? false,
  companyname: form.companyname ?? '',
  replicationStrategyId: form.replicationStrategyId ?? '',
  bpartnerId: form.bpartnerId ?? ''
})

/** AD_OrgInfo part → `/api/admin/organizations/:id/organization-info` (and the store body) */
export const organizationInfoBody = (form: any) => ({
  DUNS: form.DUNS ?? '',
  taxID: form.taxID ?? '',
  subtitle: form.subtitle ?? '',
  phone: form.phone ?? '',
  phone2: form.phone2 ?? '',
  fax: form.fax ?? '',
  eMail: form.eMail ?? '',
  receiptFooterMsg: form.receiptFooterMsg ?? '',
  timeZone: form.timeZone ?? '',
  locationId: form.location?.id ?? '',
  warehouseId: form.warehouseId ?? '',
  dropShipWarehouseId: form.dropShipWarehouseId ?? '',
  orgTypeId: form.orgTypeId ?? '',
  supervisorId: form.supervisorId ?? '',
  parentOrgId: form.parentOrgId ?? '',
  calendarId: form.calendarId ?? '',
  transferBankId: form.transferBankId ?? '',
  transferCashBookId: form.transferCashBookId ?? ''
})

/** Keys of `body` whose value differs from `snapshotBody` (deep-equal via JSON). */
export const pickChanged = (body: any, snapshotBody: any) => {
  const out: any = {}
  for (const k of Object.keys(body || {})) {
    if (!snapshotBody || JSON.stringify(body[k] ?? '') !== JSON.stringify(snapshotBody[k] ?? '')) out[k] = body[k]
  }
  return out
}

export const hasOrganizationAddress = (loc: any) =>
  !!String(loc?.address1 || loc?.city || loc?.postal || '').trim()

/**
 * Creates or updates the org's C_Location via the existing settings routes and returns its id
 * ('' when nothing to save). New locations are created org-neutral (AD_Org_ID 0) like LogYou's own.
 */
export const saveOrganizationLocation = async (loc: any) => {
  if (!hasOrganizationAddress(loc)) return loc?.id || ''
  const body: any = {
    isActive: true,
    address1: loc.address1 || '',
    address2: loc.address2 || '',
    address3: '',
    address4: '',
    city: loc.city || '',
    postal: loc.postal || '',
    regionName: loc.region || '',
    countryId: loc.countryId || '',
    regionId: loc.regionId || '',
    isValid: false
  }
  if (loc.id) {
    const res: any = await $fetch('/api/settings/locations/update', {
      method: 'PUT', headers: useRequestHeaders(['cookie']), body: { ...body, id: loc.id }
    })
    if (Number(res?.status) !== 200) throw new Error(res?.message || 'Address update failed')
    return loc.id
  }
  const res: any = await $fetch('/api/settings/locations/store', {
    method: 'POST', headers: useRequestHeaders(['cookie']), body: { ...body, organizationId: 0 }
  })
  if (Number(res?.status) !== 200 || !res?.id) throw new Error(res?.message || 'Address create failed')
  return res.id
}

export const logoDataUrl = (b64: string) => {
  const s = String(b64 || '')
  if (!s) return ''
  if (s.startsWith('data:')) return s
  const mime = s.startsWith('/9j/') ? 'image/jpeg' : s.startsWith('PHN2Zy') || s.startsWith('PD94bWwg') ? 'image/svg+xml' : s.startsWith('R0lGOD') ? 'image/gif' : 'image/png'
  return `data:${mime};base64,${s}`
}
