import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate, auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  createQuotationFollowup,
  getQuotationDetail,
  listQuotationFollowups,
  softDeleteQuotationFollowup,
  updateQuotationFollowup
} from '@/features/crm/quotations/server/service';
import { quotationFollowupSchema } from '@/features/crm/quotations/schemas/quotation.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const updateSchema = quotationFollowupSchema.extend({
  id: z.string().min(1, 'Follow-up id is required')
});

const deleteSchema = z.object({
  id: z.string().min(1, 'Follow-up id is required')
});

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationRead
    });
    const items = await listQuotationFollowups(id, organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Quotation 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 quotation follow-ups' }, { status: 500 });
  }
}

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationFollowupManage
    });
    const payload = quotationFollowupSchema.parse(await request.json());
    const quotation = await getQuotationDetail(id, organization.id);
    const created = await createQuotationFollowup(id, organization.id, session.user.id, payload);

    await auditCreate({
      organizationId: organization.id,
      branchId: quotation.branchId,
      userId: session.user.id,
      entityType: 'crm_quotation_followup',
      entityId: created.id,
      afterData: created
    });

    return NextResponse.json(
      {
        success: true,
        message: 'Quotation 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 quotation follow-up' }, { status: 500 });
  }
}

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationFollowupManage
    });
    const payload = updateSchema.parse(await request.json());
    const quotation = await getQuotationDetail(id, organization.id);
    const before = (await listQuotationFollowups(id, organization.id)).find(
      (item) => item.id === payload.id
    );

    if (!before) {
      return NextResponse.json({ message: 'Quotation follow-up not found' }, { status: 404 });
    }

    const updated = await updateQuotationFollowup(
      id,
      payload.id,
      organization.id,
      session.user.id,
      payload
    );

    await auditUpdate({
      organizationId: organization.id,
      branchId: quotation.branchId,
      userId: session.user.id,
      entityType: 'crm_quotation_followup',
      entityId: payload.id,
      beforeData: before,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Quotation follow-up updated successfully',
      followup: updated
    });
  } 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 update quotation follow-up' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationFollowupManage
    });
    const payload = deleteSchema.parse(await request.json());
    const quotation = await getQuotationDetail(id, organization.id);
    const before = (await listQuotationFollowups(id, organization.id)).find(
      (item) => item.id === payload.id
    );

    if (!before) {
      return NextResponse.json({ message: 'Quotation follow-up not found' }, { status: 404 });
    }

    const updated = await softDeleteQuotationFollowup(
      id,
      payload.id,
      organization.id,
      session.user.id
    );

    await auditDelete({
      organizationId: organization.id,
      branchId: quotation.branchId,
      userId: session.user.id,
      entityType: 'crm_quotation_followup',
      entityId: payload.id,
      beforeData: before,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Quotation follow-up deleted successfully'
    });
  } 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 delete quotation follow-up' }, { status: 500 });
  }
}
