/**
 * POST /enquiries — public, unauthenticated, no version prefix (§1, §4a).
 * Validation failure -> HTTP 422 in the `{ ok:false, error, fields }` shape the
 * frontend's enquiryResponseSchema parses (M1). `fields` keys are EnquiryInput
 * field names so the form can attach errors to the right inputs.
 */
import { Router } from 'express';
import { asyncHandler } from '../../lib/asyncHandler';
import { AppError } from '../../lib/AppError';
import { enquiryInputSchema } from './enquiry.schema';
import { createEnquiry } from './enquiry.service';

export const enquiryRouter = Router();

enquiryRouter.post(
  '/enquiries',
  asyncHandler(async (req, res) => {
    const parsed = enquiryInputSchema.safeParse(req.body);
    if (!parsed.success) {
      const fields: Record<string, string> = {};
      for (const issue of parsed.error.issues) {
        const key = typeof issue.path[0] === 'string' ? issue.path[0] : '_';
        if (!fields[key]) fields[key] = issue.message;
      }
      throw AppError.enquiryValidation(fields);
    }

    const result = await createEnquiry(parsed.data, {
      ip: req.ip ?? 'unknown',
      userAgent: req.get('user-agent') ?? undefined,
      referer: req.get('referer') ?? undefined,
    });
    res.status(200).json(result);
  }),
);
