import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } 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) => {
    const { restaurantId, branchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listStaff({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? 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) => {
      const member = await createStaffMember(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ staff: member }, { status: 201 });
    })
  )
);
