import { NextResponse } from 'next/server';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listYachts, createYacht } from '@/lib/services/yachts.service';
import { listYachtsSchema, createYachtSchema } from '@/lib/validators/yachts';

export const listHandler: RouteHandler = async (req, ctx) => {
  try {
    const query = parseQuery(req, listYachtsSchema);
    const result = await listYachts(ctx.portId, query);
    const { page, limit } = query;
    const totalPages = Math.ceil(result.total / limit);
    return NextResponse.json({
      data: result.data,
      pagination: {
        page,
        pageSize: limit,
        total: result.total,
        totalPages,
        hasNextPage: page < totalPages,
        hasPreviousPage: page > 1,
      },
    });
  } catch (error) {
    return errorResponse(error);
  }
};

export const createHandler: RouteHandler = async (req, ctx) => {
  try {
    const body = await parseBody(req, createYachtSchema);
    const yacht = await createYacht(ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: yacht }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
};
