import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  deleteApprovalReminderPolicy,
  updateApprovalReminderPolicy
} from '@/features/foundation/approval-automation/server/service';
import { approvalReminderPolicySchema } from '@/features/foundation/approval-automation/schemas';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function PATCH(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalReminderManage
    });
    const { id } = await context.params;
    const payload = approvalReminderPolicySchema.parse(await request.json());
    await updateApprovalReminderPolicy(id, organization.id, session.user.id, payload);

    return NextResponse.json({
      success: true,
      message: 'Approval reminder policy updated 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 update approval reminder policy' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  _request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalReminderManage
    });
    const { id } = await context.params;
    await deleteApprovalReminderPolicy(id, organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      message: 'Approval reminder policy deleted successfully'
    });
  } 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 delete approval reminder policy' },
      { status: 500 }
    );
  }
}
