import { NextRequest, NextResponse } from 'next/server';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { getDatabaseErrorMessage } from '@/lib/db-errors';
import {
  createEmployeeForOrganization,
  getEmployeeOptionsForOrganization,
  listEmployeesForOrganization
} from '@/features/employees/server/employee-data';
import type { EmployeeMutationPayload } from '@/features/employees/api/types';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess();
    const mode = request.nextUrl.searchParams.get('mode');

    if (mode === 'options') {
      const employees = await getEmployeeOptionsForOrganization(organization.id);
      return NextResponse.json({ employees });
    }

    const { searchParams } = request.nextUrl;
    const result = await listEmployeesForOrganization({
      organizationId: organization.id,
      filters: {
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(searchParams.get('limit') ?? 10),
        search: searchParams.get('search') ?? undefined,
        statuses: searchParams.get('statuses') ?? undefined,
        sort: searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Employees loaded successfully',
      total_employees: result.total,
      offset: result.offset,
      limit: result.limit,
      employees: result.employees
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: getDatabaseErrorMessage(error) }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess();
    const body = (await request.json()) as EmployeeMutationPayload;
    const employee = await createEmployeeForOrganization({
      organizationId: organization.id,
      payload: body
    });

    if (!employee) {
      return NextResponse.json({ message: 'Unable to create employee' }, { status: 400 });
    }

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Employee created successfully',
      employee
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: getDatabaseErrorMessage(error) }, { status: 500 });
  }
}
