import { authenticate } from '../../plugins/auth.js'
import { getCustomerById, updateCustomerDisplayName } from '../../services/customer.service.js'
import {
  completeCustomerPhoneSignIn,
  signInWithGoogle,
  signInWithApple,
} from '../../services/auth.service.js'
import { requestOtp, verifyOtp } from '../../services/otp.service.js'
import { UserType } from '../../constants.js'

const extractDeviceInfo = (request) => ({
  user_agent: request.headers['user-agent'] || null,
  ip: request.ip || null,
})

const sendAuthError = (reply, err) => {
  if (!err.statusCode) reply.request.log.error({ err }, 'Unhandled auth error')
  return reply.code(err.statusCode || 500).send({
    success: false,
    error: {
      code: err.code || 'INTERNAL',
      message: err.message,
      ...(err.details && { details: err.details }),
    },
  })
}

export const clientAuthRoutes = async (app) => {
  // --- Phone OTP ---

  app.post('/otp/request', async (request, reply) => {
    const { phone, channel } = request.body || {}
    try {
      const result = await requestOtp({
        phone,
        userType: UserType.CUSTOMER,
        ipAddress: request.ip,
        channel,
      })
      return reply.send({ success: true, data: result })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  app.post('/otp/verify', async (request, reply) => {
    const { otp_request_id, code, anonymous_customer_id } = request.body || {}
    try {
      const { phone, user_type } = await verifyOtp({ otpRequestId: otp_request_id, code })
      if (user_type !== UserType.CUSTOMER) {
        return reply.code(400).send({
          success: false,
          error: { code: 'WRONG_FLOW', message: 'This OTP was issued for a different user type' },
        })
      }
      const { tokens, profile } = await completeCustomerPhoneSignIn({
        phone,
        anonymousCustomerId: anonymous_customer_id || null,
        deviceInfo: extractDeviceInfo(request),
      })
      return reply.send({ success: true, data: { ...tokens, profile } })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  // --- Google ---

  app.post('/google', async (request, reply) => {
    const { id_token, anonymous_customer_id } = request.body || {}
    if (!id_token) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
      })
    }
    try {
      const { tokens, profile } = await signInWithGoogle({
        idToken: id_token,
        anonymousCustomerId: anonymous_customer_id || null,
        deviceInfo: extractDeviceInfo(request),
      })
      return reply.send({ success: true, data: { ...tokens, profile } })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  // --- Apple ---

  app.post('/apple', async (request, reply) => {
    const { id_token, anonymous_customer_id } = request.body || {}
    if (!id_token) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
      })
    }
    try {
      const { tokens, profile } = await signInWithApple({
        idToken: id_token,
        anonymousCustomerId: anonymous_customer_id || null,
        deviceInfo: extractDeviceInfo(request),
      })
      return reply.send({ success: true, data: { ...tokens, profile } })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  // --- Current user profile ---

  app.get('/me', { preHandler: authenticate }, async (request, reply) => {
    if (request.auth.userType !== UserType.CUSTOMER) {
      return reply.code(403).send({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Customer account required' },
      })
    }
    const customer = await getCustomerById(request.auth.userId)
    if (!customer) {
      return reply.code(404).send({
        success: false,
        error: { code: 'NOT_FOUND', message: 'Customer account not found' },
      })
    }
    return reply.send({ success: true, data: customer })
  })

  // --- Update display name ---

  app.patch('/profile', { preHandler: authenticate }, async (request, reply) => {
    if (request.auth.userType !== UserType.CUSTOMER) {
      return reply.code(403).send({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Customer account required' },
      })
    }
    const { display_name } = request.body || {}
    if (!display_name || typeof display_name !== 'string' || display_name.trim().length === 0) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'display_name is required' },
      })
    }
    const updated = await updateCustomerDisplayName(request.auth.userId, display_name.trim())
    return reply.send({ success: true, data: updated })
  })
}
