import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { leadFollowupSchema } from '@/features/crm/leads/schemas/lead.schema';
import {
  buildLeadAccessContext,
  createLeadFollowup,
  listLeadFollowups
} from '@/features/crm/leads/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadRead
    });
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const items = await listLeadFollowups(id, organization.id, accessContext);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Lead follow-ups loaded successfully',
      items
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to load lead follow-ups' }, { status: 500 });
  }
}

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadUpdate
    });
    const payload = leadFollowupSchema.parse(await request.json());
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const created = await createLeadFollowup(
      id,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

    return NextResponse.json(
      {
        success: true,
        message: 'Lead follow-up created successfully',
        followup: created
      },
      { status: 201 }
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to create lead follow-up' }, { status: 500 });
  }
}
