import { NextResponse } from 'next/server';
import { z } from 'zod';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody, parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { addMembership, listByCompany } from '@/lib/services/company-memberships.service';
import { addMembershipSchema } from '@/lib/validators/company-memberships';

const listQuerySchema = z.object({
  activeOnly: z
    .enum(['true', 'false'])
    .default('true')
    .transform((v) => v === 'true'),
});

export const listHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const { activeOnly } = parseQuery(req, listQuerySchema);
    const memberships = await listByCompany(params.id!, ctx.portId, { activeOnly });
    return NextResponse.json({ data: memberships });
  } catch (error) {
    return errorResponse(error);
  }
};

export const createHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const body = await parseBody(req, addMembershipSchema);
    const membership = await addMembership(params.id!, ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: membership }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
};
