/**
 * Unit tests for WhatsApp Availability API
 * GET /api/whatsapp/availability
 */

// 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-availability.service", () => ({
  getAvailableSlots: jest.fn(),
}));

jest.mock("@/lib/validators/whatsapp-ai.validator", () => ({
  AvailabilityQuerySchema: {
    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 { getAvailableSlots } from "@/lib/services/whatsapp-availability.service";
import { AvailabilityQuerySchema } from "@/lib/validators/whatsapp-ai.validator";

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

  beforeAll(async () => {
    availModule = await import("@/app/api/whatsapp/availability/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 availModule.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 availModule.GET(mockRequest("Bearer bad-token"));
    expect(response.status).toBe(401);
  });

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

    const response = await availModule.GET(mockRequest("Bearer valid-token"));
    expect(response.status).toBe(400);
  });

  it("should return available slots for a weekday", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "org-1",
        date: "2026-03-02",
        duration: 30,
      },
    });
    (getAvailableSlots as jest.Mock).mockResolvedValue({
      date: "2026-03-02",
      timezone: "Asia/Riyadh",
      slots: [
        { startTime: "09:00", endTime: "09:30", available: true },
        { startTime: "09:30", endTime: "10:00", available: true },
        { startTime: "10:00", endTime: "10:30", available: false },
        { startTime: "10:30", endTime: "11:00", available: true },
      ],
    });

    const response = await availModule.GET(
      mockRequest("Bearer valid-token", {
        organizationId: "org-1",
        date: "2026-03-02",
        duration: "30",
      }),
    );
    const body = (await response.json()) as Record<string, unknown>;
    expect(body.success).toBe(true);
    const data = body.data as Record<string, unknown>;
    const summary = data.summary as Record<string, number>;
    expect(summary.totalSlots).toBe(4);
    expect(summary.availableSlots).toBe(3);
    expect(summary.bookedSlots).toBe(1);
  });

  it("should mark conflicting slots as unavailable", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { organizationId: "org-1", date: "2026-03-02", duration: 30 },
    });
    (getAvailableSlots as jest.Mock).mockResolvedValue({
      date: "2026-03-02",
      timezone: "Asia/Riyadh",
      slots: [
        { startTime: "09:00", endTime: "09:30", available: true },
        { startTime: "10:00", endTime: "10:30", available: false },
      ],
    });

    const response = await availModule.GET(mockRequest("Bearer valid-token"));
    const body = (await response.json()) as Record<string, unknown>;
    const data = body.data as Record<string, unknown>;
    const slots = data.slots as Array<Record<string, unknown>>;
    const unavailable = slots.filter((s) => !s.available);
    expect(unavailable).toHaveLength(1);
    expect(unavailable[0].startTime).toBe("10:00");
  });

  it("should return empty slots for closed day", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { organizationId: "org-1", date: "2026-03-06", duration: 30 },
    });
    (getAvailableSlots as jest.Mock).mockResolvedValue({
      date: "2026-03-06",
      timezone: "Asia/Riyadh",
      slots: [],
      closed: true,
    });

    const response = await availModule.GET(mockRequest("Bearer valid-token"));
    const body = (await response.json()) as Record<string, unknown>;
    const data = body.data as Record<string, unknown>;
    const summary = data.summary as Record<string, number>;
    expect(summary.availableSlots).toBe(0);
    expect(summary.totalSlots).toBe(0);
  });

  it("should pass duration to availability service", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { organizationId: "org-1", date: "2026-03-02", duration: 60 },
    });
    (getAvailableSlots as jest.Mock).mockResolvedValue({
      date: "2026-03-02",
      timezone: "Asia/Riyadh",
      slots: [],
    });

    await availModule.GET(mockRequest("Bearer valid-token"));

    expect(getAvailableSlots).toHaveBeenCalledWith(
      expect.objectContaining({ duration: 60 }),
    );
  });

  it("should return fewer slots for non-existent org (empty)", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "non-existent",
        date: "2026-03-02",
        duration: 30,
      },
    });
    (getAvailableSlots as jest.Mock).mockResolvedValue({
      date: "2026-03-02",
      timezone: "Asia/Riyadh",
      slots: [],
    });

    const response = await availModule.GET(mockRequest("Bearer valid-token"));
    const body = (await response.json()) as Record<string, unknown>;
    const data = body.data as Record<string, unknown>;
    const slots = data.slots as unknown[];
    expect(slots).toHaveLength(0);
  });

  it("should return 500 on service error", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (AvailabilityQuerySchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: { organizationId: "org-1", date: "2026-03-02", duration: 30 },
    });
    (getAvailableSlots as jest.Mock).mockRejectedValue(new Error("DB error"));

    const response = await availModule.GET(mockRequest("Bearer valid-token"));
    expect(response.status).toBe(500);
  });
});
