import { NextRequest, NextResponse } from 'next/server';
import { listMasterOptions } from '@/features/foundation/master-options/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.organizationManage
    });
    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 category = searchParams.get('category') ?? undefined;
    const sort = searchParams.get('sort') ?? undefined;
    const result = await listMasterOptions({
      organizationId: organization.id,
      page,
      limit,
      search,
      category,
      sort
    });
    const offset = (page - 1) * limit;

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Master options loaded successfully',
      total_items: result.totalItems,
      offset,
      limit,
      items: result.items.map((item) => ({
        id: item.id,
        organization_id: item.organizationId,
        category: item.category,
        code: item.code,
        label: item.label,
        value: item.value,
        parent_id: item.parentId,
        parent_label: item.parentLabel,
        sort_order: item.sortOrder,
        is_active: item.isActive,
        deleted_at: item.deletedAt,
        updated_at: item.updatedAt
      }))
    });
  } 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 master options' }, { status: 500 });
  }
}
