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

const masterOptionSchema = z.object({
  category: z.string().min(1),
  code: z.string().min(1),
  label: z.string().min(1),
  value: z.string().nullable().optional(),
  parent_id: z.string().nullable().optional(),
  sort_order: z.number().int().optional(),
  is_active: z.boolean().optional(),
  metadata: z.record(z.string(), z.unknown()).nullable().optional()
});

function mapMasterOptionResponse(item: Awaited<ReturnType<typeof createMasterOption>>) {
  return {
    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,
    metadata: item.metadata,
    deleted_at: item.deletedAt,
    created_at: item.createdAt,
    updated_at: item.updatedAt
  };
}

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmMasterOptionRead
    });
    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
    });

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

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmMasterOptionCreate
    });
    const payload = masterOptionSchema.parse(await request.json());
    const created = await createMasterOption(organization.id, {
      category: payload.category,
      code: payload.code,
      label: payload.label,
      value: payload.value,
      parentId: payload.parent_id,
      sortOrder: payload.sort_order,
      isActive: payload.is_active,
      metadata: payload.metadata
    });

    await auditCreate({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'ms_option',
      entityId: created.id,
      afterData: created
    });

    return NextResponse.json({
      success: true,
      message: 'Master option created successfully'
    });
  } 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.flatten().formErrors.join(', ') }, { status: 400 });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to create master option' }, { status: 500 });
  }
}
