/**
 * Unit tests for WhatsApp Company Identification API
 * GET /api/whatsapp/identify-company
 */

// Mock dependencies BEFORE imports
jest.mock("@/lib/logger", () => ({
  logger: {
    warn: jest.fn(),
    error: jest.fn(),
    info: jest.fn(),
    debug: jest.fn(),
  },
}));

jest.mock("@/lib/db");

jest.mock("@/lib/services/system-settings.service", () => ({
  systemSettingsService: {
    validateN8NToken: jest.fn(),
  },
}));

jest.mock("@/lib/services/whatsapp-company-identification.service", () => ({
  identifyCompanyByPhone: jest.fn(),
}));

jest.mock("@/lib/validators/whatsapp-ai.validator", () => ({
  CompanyIdentificationQuerySchema: {
    safeParse: jest.fn(),
  },
}));

jest.mock("next/server", () => {
  const NextResponseMock = function (
    body: string | null,
    init?: Record<string, unknown>,
  ) {
    return {
      status: (init?.status as number) || 200,
      headers: new Map(
        Object.entries((init?.headers as Record<string, string>) || {}),
      ),
      json: async () => (body ? JSON.parse(body) : null),
    };
  };
  NextResponseMock.json = jest.fn(
    (data: unknown, options?: { status?: number }) => ({
      status: options?.status || 200,
      headers: new Map(),
      json: async () => data,
    }),
  );
  return { NextRequest: jest.fn(), NextResponse: NextResponseMock };
});

import { NextRequest, NextResponse } from "next/server";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { identifyCompanyByPhone } from "@/lib/services/whatsapp-company-identification.service";
import { CompanyIdentificationQuerySchema } from "@/lib/validators/whatsapp-ai.validator";

// Route not yet implemented
describe.skip("GET /api/whatsapp/identify-company", () => {
  let identifyModule: {
    GET: (req: unknown) => Promise<{
      status: number;
      json: () => Promise<Record<string, unknown>>;
    }>;
  };

  beforeAll(async () => {
    identifyModule = await import("@/app/api/whatsapp/identify-company/route");
  });

  beforeEach(() => {
    jest.clearAllMocks();
    (NextResponse.json as jest.Mock).mockImplementation(
      (data: unknown, options?: { status?: number }) => ({
        status: options?.status || 200,
        headers: new Map(),
        json: async () => data,
      }),
    );
  });

  const mockRequest = (authHeader?: string, params?: Record<string, string>) =>
    ({
      headers: {
        get: jest.fn((key: string) => {
          if (key === "authorization") return authHeader || null;
          return null;
        }),
      },
      nextUrl: {
        searchParams: new URLSearchParams(params || {}),
      },
    }) as unknown as NextRequest;

  it("should return 401 without auth", async () => {
    const response = await identifyModule.GET(mockRequest());
    expect(response.status).toBe(401);
  });

  it("should return 401 with invalid token", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      false,
    );

    const response = await identifyModule.GET(mockRequest("Bearer bad-token"));
    expect(response.status).toBe(401);
  });

  it("should return 400 for missing phone parameter", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (CompanyIdentificationQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: false,
      error: { errors: [{ message: "Required" }] },
    });

    const response = await identifyModule.GET(
      mockRequest("Bearer valid-token"),
    );
    const body = await response.json();
    expect(response.status).toBe(400);
    expect(body.error).toBe("Invalid request");
  });

  it("should return 400 for invalid phone format", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (CompanyIdentificationQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: false,
      error: { errors: [{ message: "Invalid phone number" }] },
    });

    const response = await identifyModule.GET(
      mockRequest("Bearer valid-token", { phone: "abc" }),
    );
    expect(response.status).toBe(400);
  });

  it("should identify company by WhatsApp phone number ID", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (CompanyIdentificationQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { phone: "1234567890" },
    });
    (identifyCompanyByPhone as jest.Mock).mockResolvedValue({
      companyId: "org-1",
      name: "Test Clinic",
      subscriptionTier: "professional",
      tierLevel: 2,
      features: { aiAgent: true, payments: true, appointments: true },
      whatsappConfig: { phoneNumberId: "1234567890" },
    });

    const response = await identifyModule.GET(
      mockRequest("Bearer valid-token", { phone: "1234567890" }),
    );
    const body = await response.json();
    expect(body.success).toBe(true);
    expect(body.data.companyId).toBe("org-1");
    expect(body.data.subscriptionTier).toBe("professional");
    expect(body.data.features.aiAgent).toBe(true);
  });

  it("should return 404 for unregistered phone number", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (CompanyIdentificationQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { phone: "9999999999" },
    });
    (identifyCompanyByPhone as jest.Mock).mockResolvedValue(null);

    const response = await identifyModule.GET(
      mockRequest("Bearer valid-token", { phone: "9999999999" }),
    );
    const body = await response.json();
    expect(response.status).toBe(404);
    expect(body.error).toBe("Company not found");
  });

  it("should return 500 on service error", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (CompanyIdentificationQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { phone: "1234567890" },
    });
    (identifyCompanyByPhone as jest.Mock).mockRejectedValue(
      new Error("DB error"),
    );

    const response = await identifyModule.GET(
      mockRequest("Bearer valid-token", { phone: "1234567890" }),
    );
    expect(response.status).toBe(500);
  });
});
