import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { create, listForInterest } from '@/lib/services/interest-contact-log.service';
import { createContactLogSchema } from '@/lib/validators/interest-contact-log';

export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const entries = await listForInterest(params.id!, ctx.portId);
      return NextResponse.json({ data: entries });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, createContactLogSchema);
      const entry = await create(ctx.userId, {
        interestId: params.id!,
        occurredAt: body.occurredAt,
        channel: body.channel,
        direction: body.direction,
        summary: body.summary,
        voiceTranscript: body.voiceTranscript ?? null,
        templateUsed: body.templateUsed ?? null,
        followUpAt: body.followUpAt ?? null,
      });
      return NextResponse.json({ data: entry }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
