import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { listApprovalRequests, submitForApproval } from '@/features/foundation/approval/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const submitApprovalSchema = z.object({
  workflowCode: z.string().optional(),
  entityType: z.string().min(1, 'Entity type is required'),
  entityId: z.string().min(1, 'Entity id is required'),
  remark: z.string().optional()
});

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalRead
    });
    const { searchParams } = request.nextUrl;
    const page = Number(searchParams.get('page') ?? 1);
    const limit = Number(searchParams.get('limit') ?? 10);
    const search = searchParams.get('search') ?? undefined;
    const status = searchParams.get('status') ?? undefined;
    const entityType = searchParams.get('entityType') ?? undefined;
    const entityId = searchParams.get('entityId') ?? undefined;
    const sort = searchParams.get('sort') ?? undefined;
    const result = await listApprovalRequests(organization.id, {
      page,
      limit,
      search,
      status,
      entityType,
      entityId,
      sort
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Approvals loaded successfully',
      totalItems: result.totalItems,
      offset: (page - 1) * limit,
      limit,
      items: result.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 approvals' }, { status: 500 });
  }
}

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

    return NextResponse.json(
      {
        success: true,
        message: 'Approval request submitted successfully',
        approvalRequest: 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 submit approval request' }, { status: 500 });
  }
}
