import { NextResponse } from "next/server";
import {
  createApiResponse,
  createApiError,
  createPaginationMeta,
  withApiLogging,
  handleCorsPreflightRequest,
  addCorsHeaders
} from "../helpers.js";
import { authenticateRequest, hasRequiredScope } from "../auth/dual-auth.js";
import { PatternUsageService } from "../../services/index.js";
import { queryOneWithRLS } from "../../db.js";
function createPatternUsagesHandlers() {
  async function OPTIONS() {
    return handleCorsPreflightRequest();
  }
  const GET = withApiLogging(
    async (req, { params }) => {
      try {
        const authResult = await authenticateRequest(req);
        if (!authResult.success) {
          return NextResponse.json(
            { success: false, error: "Authentication required", code: "AUTHENTICATION_FAILED" },
            { status: 401 }
          );
        }
        if (authResult.rateLimitResponse) {
          return authResult.rateLimitResponse;
        }
        if (!hasRequiredScope(authResult, "patterns:read")) {
          const response2 = createApiError("Insufficient permissions", 403);
          return addCorsHeaders(response2);
        }
        const { id: patternId } = await params;
        const userId = authResult.user.id;
        if (!patternId || patternId.trim() === "") {
          const response2 = createApiError("Pattern ID is required", 400, null, "MISSING_PATTERN_ID");
          return addCorsHeaders(response2);
        }
        const pattern = await queryOneWithRLS(
          'SELECT id FROM "patterns" WHERE id = $1',
          [patternId],
          userId
        );
        if (!pattern) {
          const response2 = createApiError("Pattern not found", 404, null, "PATTERN_NOT_FOUND");
          return addCorsHeaders(response2);
        }
        const url = new URL(req.url);
        const entityType = url.searchParams.get("entityType") || void 0;
        const limit = Math.min(parseInt(url.searchParams.get("limit") || "50", 10), 100);
        const page = Math.max(parseInt(url.searchParams.get("page") || "1", 10), 1);
        const offset = (page - 1) * limit;
        const result = await PatternUsageService.getUsagesWithEntityInfo(
          patternId,
          userId,
          { entityType, limit, offset }
        );
        const totalPages = Math.ceil(result.total / limit);
        const paginationMeta = createPaginationMeta(page, limit, result.total);
        const response = createApiResponse({
          usages: result.usages,
          counts: result.counts,
          total: result.total
        }, {
          ...paginationMeta,
          totalPages,
          patternId,
          entityType: entityType || "all"
        });
        return addCorsHeaders(response);
      } catch (error) {
        console.error("Error fetching pattern usages:", error);
        const response = createApiError("Internal server error", 500);
        return addCorsHeaders(response);
      }
    }
  );
  return { GET, OPTIONS };
}
export {
  createPatternUsagesHandlers
};
