import { NextRequest, NextResponse } from 'next/server';
import {
  createPermissionTemplateForOrganization,
  listPermissionTemplatesForOrganization
} from '@/features/permission-management/server/permission-template-data';
import { permissionTemplateSchema } from '@/features/permission-management/schemas/permission-template';
import { AuthError, requireSuperAdminOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireSuperAdminOrganizationAccess();
    const result = await listPermissionTemplatesForOrganization({
      organizationId: organization.id,
      filters: {
        page: Number(request.nextUrl.searchParams.get('page') ?? 1),
        limit: Number(request.nextUrl.searchParams.get('limit') ?? 10),
        search: request.nextUrl.searchParams.get('search') ?? undefined,
        status: request.nextUrl.searchParams.get('status') ?? undefined,
        sort: request.nextUrl.searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Loaded permission templates successfully',
      total_permission_templates: result.total,
      offset: result.offset,
      limit: result.limit,
      permission_templates: result.permissionTemplates
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load permission templates' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const body = permissionTemplateSchema.parse(await request.json());
    const templateId = await createPermissionTemplateForOrganization({
      organizationId: organization.id,
      actorUserId: session.user.id,
      payload: body
    });

    return NextResponse.json(
      {
        success: true,
        message: 'Permission template created successfully',
        template_id: templateId
      },
      { status: 201 }
    );
  } 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 create permission template' }, { status: 500 });
  }
}
