import { isAdminVerified } from '../../../utils/mobileReleases'
import { invalidateDialer } from '../../../utils/telephony/dialAccess'
import { normalizeQualifyPatch } from '../../../utils/leads/leadQualification'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.supervisorId) {
    newObjValue = {...newObjValue, 
      Supervisor_ID: {
        id: body.supervisorId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.notificationTypeId) {
    newObjValue = {...newObjValue, 
      NotificationType: {
        id: body.notificationTypeId
      }
    }
  }
  if(body.greetingId) {
    newObjValue = {...newObjValue, 
      C_Greeting_ID: {
        id: body.greetingId,
        tableName: 'C_Greeting'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.orgTrxId) {
    newObjValue = {...newObjValue, 
      AD_OrgTrx_ID: {
        id: body.orgTrxId,
        tableName: 'AD_Org'
      }
    }
  }
  if(body.jobId) {
    newObjValue = {...newObjValue, 
      C_Job_ID: {
        id: body.jobId,
        tableName: 'C_Job'
      }
    }
  }
  if(body.isMenuAutoExpandId) {
    newObjValue = {...newObjValue, 
      IsMenuAutoExpand: {
        id: body.isMenuAutoExpandId
      }
    }
  }
  if(body.mailTextId) {
    newObjValue = {...newObjValue, 
      R_DefaultMailText_ID: {
        id: body.mailTextId,
        tableName: 'R_Mailtext'
      }
    }
  }
  if(body.positionId) {
    newObjValue = {...newObjValue, 
      C_Job_ID: {
        id: body.positionId,
        tableName: 'C_Job'
      }
    }
  }
  if(body.datePasswordChanged) {
    newObjValue = {...newObjValue, 
      datePasswordChanged: body.datePasswordChanged
    }
  }
  if(body.eMailVerifyDate) {
    newObjValue = {...newObjValue, 
      eMailVerifyDate: body.eMailVerifyDate
    }
  }
  if(body.imageId || body.image) {
    newObjValue = {...newObjValue, 
      AD_Image_ID: {
        id: body.imageId,
        data: body.image,
        tableName: 'AD_Image'
      }
    }
  }
  if(body.locationId) {
    newObjValue = {...newObjValue, 
      C_Location_ID: {
        id: body.locationId,
        tableName: 'C_Location'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.leadSourceId) {
    newObjValue = {...newObjValue, 
      LeadSource: {
        id: body.leadSourceId
      }
    }
  }
  if(body.leadStatusId) {
    newObjValue = {...newObjValue, 
      LeadStatus: {
        id: body.leadStatusId
      }
    }
  }
  if(body.leadSourceDescription) {
    newObjValue = {...newObjValue, 
      LeadSourceDescription: body.leadSourceDescription
    }
  }
  if(body.leadStatusDescription) {
    newObjValue = {...newObjValue, 
      LeadStatusDescription: body.leadStatusDescription
    }
  }
  if(body.isSystemUser) {
    newObjValue = {...newObjValue, 
      isSystemUser: body.isSystemUser
    }
  }
  // SIP_Extension (click-to-dial): only when the client sent the key — the
  // pages include it only for admins editing a system user, so a save by a
  // non-admin never clears it. Server-authoritative admin check on top.
  if(Object.prototype.hasOwnProperty.call(body, 'sipExtension')) {
    const admin = await isAdminVerified(event, token)
    if(admin) {
      const ext = String(body.sipExtension ?? '').replace(/\D+/g, '').slice(0, 10)
      newObjValue = {...newObjValue, SIP_Extension: ext }
      if(body.id) invalidateDialer(Number(body.id))
    }
  }

  const res: any = await event.context.fetch('models/ad_user', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    password: body.password,
    eMail: body.eMail,
    isFullBPAccess: body.isFullBPAccess,
    value: body.value,
    isInPayroll: body.isInPayroll,
    isSalesLead: body.isSalesLead,
    isLocked: body.isLocked,
    failedLoginCount: body.failedLoginCount,
    isNoPasswordReset: body.isNoPasswordReset,
    isExpired: body.isExpired,
    isAddMailTextAutomatically: body.isAddMailTextAutomatically,
    isNoExpire: body.isNoExpire,
    isSupportUser: body.isSupportUser,
    isShipTo: body.isShipTo,
    isBillTo: body.isBillTo,
    isVendorLead: body.isVendorLead,
    eMailUser: body.eMailUser,
    phone2: body.phone2,
    birthday: body.birthday,
    phone: body.phone,
    fax: body.fax,
    lastResult: body.lastResult,
    lastContact: body.lastContact,
    title: body.title,
    comments: body.comments,
    eMailVerify: body.eMailVerify,
    LDAPUser: body.LDAPUser,
    // Lead qualification (custom AD_User columns, see utils/leads/leadQualification.ts) —
    // only the filled values are sent (nulls are dropped: nothing to clear on a create).
    ...Object.fromEntries(Object.entries(await normalizeQualifyPatch(event, token, {
      leadRating: body.leadRating, followUpDate: body.followUpDate, followUpNote: body.followUpNote,
      monthlyOrders: body.monthlyOrders, skuCount: body.skuCount, shopSystem: body.shopSystem,
      expectedMonthlyValue: body.expectedMonthlyValue, winProbability: body.winProbability,
      expectedStartDate: body.expectedStartDate, avgParcelWeight: body.avgParcelWeight,
      leadStreet: body.leadStreet, leadZip: body.leadZip, leadCity: body.leadCity, leadCountry: body.leadCountry,
      businessModel: body.businessModel, lostReason: body.lostReason
    })).filter(([, v]) => v !== null)),
    ...newObjValue,
    tableName: 'AD_User'
  })
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})