import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createStaffSchema } from '@server/validators/staff.validator';
import { listStaff, createStaffMember } from '@server/services/staff.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'staff', 'read');

    const { restaurantId, pinnedBranchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    // Branch scoping: pinned users are always restricted to their pinned branch
    // regardless of query params. Non-pinned users (owners/admins) fall back to
    // their session's active branch or a caller-supplied branch_id filter.
    const effectiveBranchId = pinnedBranchId != null
      ? pinnedBranchId
      : (p.get('branch_id') ?? req.session.branchId ?? undefined);

    const result = await listStaff({
      restaurantId: restaurantId!,
      branchId: effectiveBranchId ?? undefined,
      role: p.get('role') ?? undefined,
      isActive: p.has('is_active') ? p.get('is_active') === 'true' : undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
    });

    return NextResponse.json({ staff: result.data, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createStaffSchema, async (req) => {
      await requireSection(req, 'staff', 'create');

      const { restaurantId, pinnedBranchId } = req.session;
      const bodyData = req.parsedBody as Record<string, unknown>;

      // If the caller is branch-pinned, force the new staff member into their
      // branch regardless of what the request body says, preventing cross-branch
      // staff creation.
      const data: Record<string, unknown> = pinnedBranchId != null
        ? { ...bodyData, branch_id: pinnedBranchId }
        : bodyData;

      const member = await createStaffMember(restaurantId!, data);
      return NextResponse.json({ staff: member }, { status: 201 });
    })
  )
);
