import * as personalContactService from '../services/personal-contact.service.js'
import { BadRequestError } from '../utils/errors.js'

const normalizePayload = (body) => ({
  firstName: body.firstName?.trim(),
  lastName: body.lastName?.trim() || null,
  phone: body.phone?.trim(),
  email: body.email?.trim(),
  secondaryEmail: body.secondaryEmail?.trim() || null,
  companyId: body.companyId || null,
  description: body.description?.trim() || null,
})

export const listPersonalContacts = async (req, res, next) => {
  try {
    const contacts = await personalContactService.listPersonalContacts(req.userId)
    res.status(200).json({ success: true, data: contacts })
  } catch (error) {
    next(error)
  }
}

export const createPersonalContact = async (req, res, next) => {
  try {
    const payload = normalizePayload(req.body)
    if (!payload.firstName || !payload.email) {
      throw new BadRequestError('firstName a email sú povinné')
    }

    const created = await personalContactService.createPersonalContact(req.userId, payload)

    res.status(201).json({ success: true, data: created })
  } catch (error) {
    next(error)
  }
}

export const updatePersonalContact = async (req, res, next) => {
  try {
    const payload = normalizePayload(req.body)

    const updated = await personalContactService.updatePersonalContact(
      req.params.contactId,
      req.userId,
      payload
    )

    res.status(200).json({ success: true, data: updated })
  } catch (error) {
    next(error)
  }
}

export const deletePersonalContact = async (req, res, next) => {
  try {
    const result = await personalContactService.deletePersonalContact(req.params.contactId, req.userId)
    res.status(200).json({ success: true, message: result.message })
  } catch (error) {
    next(error)
  }
}

export const getContactsByCompany = async (req, res, next) => {
  try {
    const { companyId } = req.params
    const contacts = await personalContactService.getContactsByCompanyId(companyId)
    res.status(200).json({ success: true, data: contacts })
  } catch (error) {
    next(error)
  }
}
