import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import {
  createApprovalWorkflow,
  listApprovalWorkflows
} from '@/features/foundation/approval/server/service';
import { BUSINESS_ROLES, PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const workflowSchema = z.object({
  code: z.string().min(1),
  name: z.string().min(1),
  entityType: z.string().min(1),
  isActive: z.boolean().optional()
});

export async function GET(_request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowRead
    });
    const items = await listApprovalWorkflows(organization.id);

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

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowCreate
    });
    const payload = workflowSchema.parse(await request.json());
    const created = await createApprovalWorkflow(organization.id, payload);

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

    return NextResponse.json({
      success: true,
      message: 'Approval workflow created successfully',
      allowedRoles: BUSINESS_ROLES
    });
  } 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 approval workflow' }, { status: 500 });
  }
}
