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

function readTemplateId(value: string) {
  const templateId = Number(value);
  if (!Number.isInteger(templateId) || templateId <= 0) {
    throw new Error('INVALID_TEMPLATE_ID');
  }
  return templateId;
}

export async function GET(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { organization } = await requireSuperAdminOrganizationAccess();
    const templateId = readTemplateId((await params).id);
    const permissionTemplate = await getPermissionTemplateById({
      organizationId: organization.id,
      templateId
    });

    return NextResponse.json({
      success: true,
      permission_template: permissionTemplate
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error && error.message === 'NOT_FOUND') {
      return NextResponse.json({ message: 'Permission template not found' }, { status: 404 });
    }

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

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const templateId = readTemplateId((await params).id);
    const body = permissionTemplateSchema.parse(await request.json());
    await updatePermissionTemplateForOrganization({
      organizationId: organization.id,
      actorUserId: session.user.id,
      templateId,
      payload: body
    });

    return NextResponse.json({
      success: true,
      message: 'Permission template updated successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error && error.message === 'NOT_FOUND') {
      return NextResponse.json({ message: 'Permission template not found' }, { status: 404 });
    }

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

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

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const templateId = readTemplateId((await params).id);
    const body = (await request.json().catch(() => ({}))) as { reason?: string };
    await softDeletePermissionTemplate({
      organizationId: organization.id,
      actorUserId: session.user.id,
      templateId,
      reason: body.reason
    });

    return NextResponse.json({
      success: true,
      message: 'Permission template deleted successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (
      error instanceof Error &&
      (error.message === 'NOT_FOUND' || error.message === 'SYSTEM_TEMPLATE_PROTECTED')
    ) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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