import { NextResponse } from 'next/server';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { endMembership, updateMembership } from '@/lib/services/company-memberships.service';
import { endMembershipSchema, updateMembershipSchema } from '@/lib/validators/company-memberships';

export const patchHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const body = await parseBody(req, updateMembershipSchema);
    const updated = await updateMembership(params.mid!, ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: updated });
  } catch (error) {
    return errorResponse(error);
  }
};

export const deleteHandler: RouteHandler = async (req, ctx, params) => {
  try {
    let endDate = new Date();
    const text = await req.text();
    if (text.length > 0) {
      const parsed = endMembershipSchema.parse(JSON.parse(text));
      endDate = parsed.endDate;
    }
    await endMembership(
      params.mid!,
      ctx.portId,
      { endDate },
      {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      },
    );
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    return errorResponse(error);
  }
};
