import { string } from 'alga-js'
import errorHandlingHelper from '../../utils/errorHandlingHelper'

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

    try {
        const config = useRuntimeConfig()
        const token = config.api.idempieretoken
        const body = await readBody(event)

        // Validate required fields
        if (!body.email) {
            data = {
                status: 400,
                message: 'Email is required',
                success: false
            }
            return data
        }

        // Configure Client and Organization IDs
        const clientId = body.ad_client_id || body.AD_Client_ID || process.env.DEFAULT_CLIENT_ID || 1000000
        const orgId = body.ad_org_id || body.AD_Org_ID || process.env.DEFAULT_ORG_ID || 1000000

        // Check if user already exists
        const res = await $fetch(config.api.url+`/models/ad_user?$filter=${string.urlEncode("eMail eq '"+body.email+"'")}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
                Authorization: 'Bearer '+token
            },
        })

        if(Number(res?.records?.length ?? 0) >= 1) {
            data = {
                status: 409,
                message: 'Lead already exists with this email',
                success: false,
                email: body.email,
                ad_client_id: clientId,
                ad_org_id: orgId
            }
            return data
        }

        // Create new lead
        const createRes = await $fetch(config.api.url+'/models/ad_user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
                Authorization: 'Bearer '+token
            },
            body: {
                AD_Client_ID: {
                    id: clientId,
                    tableName: 'AD_Client'
                },
                AD_Org_ID: {
                    id: orgId,
                    tableName: 'AD_Org'
                },
                isActive: true,
                name: `${body.names?.first_name || ''} ${body.names?.last_name || ''}`,
                description: 'Shopsystem: ' + (Array.isArray(body.multi_select_1) ? body.multi_select_1 : []).filter(Boolean).join(', '),
                eMail: body.email,
                isFullBPAccess: false,
                isInPayroll: false,
                isSalesLead: true,
                isLocked: false,
                isNoPasswordReset: false,
                isExpired: false,
                isAddMailTextAutomatically: false,
                isNoExpire: true,
                isSupportUser: false,
                isShipTo: true,
                isBillTo: false,
                isVendorLead: true,
                eMailUser: body.email,
                phone: body.phone,
                URL: body.input_text,
                comments: 'Produkte: ' + `${body.dropdown_1}` + ' Position: ' + `${body.dropdown_2}` + ' Paketgewicht: ' + `${body.input_radio_1}` + ' Zielland: ' + body.checkbox_6?.[0] || '' + body.checkbox_6?.[1] || '' + body.checkbox_6?.[2] || '' + body.checkbox_6?.[3] || '' + 'Paketmenge: ' + `${body.rangeslider}`,
                NotificationType: {
                    id: 'X'
                },
                LeadSource: {
                    id: 'EC'
                },
                LeadStatus: {
                    id: 'N'
                },
                LeadSourceDescription: body.input_radio,
                LeadStatusDescription: body._fluentform_8_fluentformnonce ?? '',
                tableName: 'AD_User'
            }
        })

        // Success response
        if(createRes && createRes.id) {
            data = {
                status: 201,
                message: 'Lead created successfully',
                success: true,
                id: createRes.id,
                email: body.email,
                name: `${body.names?.first_name || ''} ${body.names?.last_name || ''}`.trim(),
                ad_client_id: clientId,
                ad_org_id: orgId
            }
        } else {
            data = {
                status: 500,
                message: 'Failed to create lead - no ID returned',
                success: false,
                email: body.email,
                ad_client_id: clientId,
                ad_org_id: orgId
            }
        }

    } catch(err: any) {
        data = errorHandlingHelper(err?.data ?? err)
        data.success = false
        data.message = data.message || 'Internal server error while creating lead'
    }

    return data
})