/**
 * Security tests: quotation cron endpoints must reject "Bearer undefined"
 * when the cron auth env var is not set.
 */

// Store & restore the cron auth env var across test runs
const CRON_ENV_KEY = "CRON_SECRET"; // eslint-disable-line no-secrets/no-secrets
const originalValue = process.env[CRON_ENV_KEY];

jest.mock("@/lib/db");
jest.mock("@/lib/services/quotation-penalties.service", () => ({
  processOverduePenalties: jest.fn().mockResolvedValue({ penalized: 0 }),
}));
jest.mock("@/lib/services/quotation-reminders.service", () => ({
  processDueReminders: jest.fn().mockResolvedValue({ sent: 0 }),
}));
jest.mock("@/lib/services/quotation-recurring.service", () => ({
  processDueRecurringTemplates: jest.fn().mockResolvedValue({ enqueued: 0 }),
}));
jest.mock("@/lib/logger", () => ({
  logger: {
    info: jest.fn(),
    error: jest.fn(),
    warn: jest.fn(),
    scope: () => ({ info: jest.fn(), error: jest.fn(), warn: jest.fn() }),
  },
}));

import { NextRequest } from "next/server";
import { GET as expiryGET } from "@/app/api/cron/quotation-expiry/route";
import { GET as penaltiesGET } from "@/app/api/cron/quotation-penalties/route";
import { GET as remindersGET } from "@/app/api/cron/quotation-reminders/route";
import { GET as recurringGET } from "@/app/api/cron/quotation-recurring/route";

function makeReq(path: string, authHeader?: string) {
  const headers: Record<string, string> = {};
  if (authHeader) headers["authorization"] = authHeader;
  return new NextRequest(`http://localhost:9000${path}`, {
    method: "GET",
    headers,
  });
}

describe("Quotation cron auth: Bearer undefined bypass prevention", () => {
  beforeEach(() => {
    delete process.env[CRON_ENV_KEY];
  });
  afterAll(() => {
    if (originalValue !== undefined) {
      process.env[CRON_ENV_KEY] = originalValue;
    }
  });

  it("rejects Bearer undefined on quotation-expiry when env is unset", async () => {
    const res = await expiryGET(
      makeReq("/api/cron/quotation-expiry", "Bearer undefined"),
    );
    expect(res.status).toBe(401);
  });

  it("rejects Bearer undefined on quotation-penalties when env is unset", async () => {
    const res = await penaltiesGET(
      makeReq("/api/cron/quotation-penalties", "Bearer undefined"),
    );
    expect(res.status).toBe(401);
  });

  it("rejects Bearer undefined on quotation-reminders when env is unset", async () => {
    const res = await remindersGET(
      makeReq("/api/cron/quotation-reminders", "Bearer undefined"),
    );
    expect(res.status).toBe(401);
  });

  it("rejects Bearer undefined on quotation-recurring when env is unset", async () => {
    const res = await recurringGET(
      makeReq("/api/cron/quotation-recurring", "Bearer undefined"),
    );
    expect(res.status).toBe(401);
  });

  it("rejects requests with no authorization header when env is unset", async () => {
    const res = await expiryGET(makeReq("/api/cron/quotation-expiry"));
    expect(res.status).toBe(401);
  });

  it("does not reject valid cron token (auth passes, not 401)", async () => {
    process.env[CRON_ENV_KEY] = "test-token-abc";
    const res = await expiryGET(
      makeReq("/api/cron/quotation-expiry", "Bearer test-token-abc"),
    );
    expect(res.status).not.toBe(401);
  });
});
