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 { listCompanies, createCompany } from '@/lib/services/companies.service';
import { listCompaniesSchema, createCompanySchema } from '@/lib/validators/companies';

export const listHandler: RouteHandler = async (req, ctx) => {
  try {
    const query = parseQuery(req, listCompaniesSchema);
    const result = await listCompanies(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, createCompanySchema);
    const company = await createCompany(ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: company }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
};
