/**
 * Unit tests for WhatsApp Bookings API
 * POST /api/whatsapp/bookings
 */

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

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

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

jest.mock("@/lib/convex-client");

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 { prisma } from "@/lib/db";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { requireFeatureAccess } from "@/lib/services/whatsapp-feature-access.service";
import { isSlotAvailable } from "@/lib/services/whatsapp-availability.service";
import { BookingCreateSchema } from "@/lib/validators/whatsapp-ai.validator";

describe("POST /api/whatsapp/bookings", () => {
  let bookingModule: {
    POST: (req: unknown) => Promise<{
      status: number;
      json: () => Promise<Record<string, unknown>>;
    }>;
  };

  beforeAll(async () => {
    bookingModule = await import("@/app/api/whatsapp/bookings/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, body?: Record<string, unknown>) =>
    ({
      headers: {
        get: jest.fn((key: string) => {
          if (key === "authorization") return authHeader || null;
          return null;
        }),
      },
      json: jest.fn().mockResolvedValue(body || {}),
    }) as unknown as NextRequest;

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

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

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

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

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token", { customerName: "Test" }),
    );
    const body = await response.json();
    expect(response.status).toBe(400);
    expect(body.error).toBe("Invalid request");
  });

  // Route was simplified - no longer calls requireFeatureAccess
  it("should return 404 when organization not found", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (BookingCreateSchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "starter-org",
        customerName: "Test",
        customerPhone: "+966501234567",
        appointmentDate: "2026-03-02T10:00:00Z",
        duration: 30,
        language: "en",
      },
    });
    (prisma.organizations.findUnique as jest.Mock).mockResolvedValue(null);

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token"),
    );
    const body = await response.json();
    expect(response.status).toBe(404);
    expect(body.error).toBe("Organization not found");
  });

  // Route simplified - no longer checks slot availability
  it.skip("should return 409 for unavailable slot", async () => {});

  it("should return 404 for non-existent organization", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (BookingCreateSchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "non-existent",
        customerName: "Test",
        customerPhone: "+966501234567",
        appointmentDate: "2026-03-02T10:00:00Z",
        duration: 30,
        language: "en",
      },
    });
    (requireFeatureAccess as jest.Mock).mockResolvedValue(undefined);
    (isSlotAvailable as jest.Mock).mockResolvedValue(true);
    (prisma.organizations.findUnique as jest.Mock).mockResolvedValue(null);

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token"),
    );
    const body = await response.json();
    expect(response.status).toBe(404);
    expect(body.error).toBe("Organization not found");
  });

  it("should create booking successfully via convex", async () => {
    const convexClient = jest.requireMock("@/lib/convex-client");
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (BookingCreateSchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "org-1",
        customerName: "Ahmed Ali",
        customerPhone: "+966501234567",
        customerEmail: "ahmed@example.com",
        appointmentDate: "2026-03-02T10:00:00Z",
        duration: 30,
        notes: "Test booking",
        language: "en",
      },
    });
    (prisma.organizations.findUnique as jest.Mock).mockResolvedValue({
      ownerId: "owner-1",
    });
    convexClient.convexMutation.mockResolvedValue({
      id: "wa_1234567_abcdefg",
      status: "pending",
    });

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token"),
    );
    const body = await response.json();
    expect(body.success).toBe(true);
    expect(body.message).toBe("Booking confirmed");
  });

  it("should create booking with Arabic data", async () => {
    const convexClient = jest.requireMock("@/lib/convex-client");
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (BookingCreateSchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "org-1",
        customerName: "أحمد",
        customerPhone: "+966502222222",
        appointmentDate: "2026-03-02T10:00:00Z",
        duration: 30,
        language: "ar",
      },
    });
    (prisma.organizations.findUnique as jest.Mock).mockResolvedValue({
      ownerId: "owner-1",
    });
    convexClient.convexMutation.mockResolvedValue({
      id: "wa_1234567_hijklmn",
      status: "pending",
    });

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token"),
    );
    const body = await response.json();
    expect(body.success).toBe(true);
  });

  it("should return 500 on unexpected error", async () => {
    (systemSettingsService.validateN8NToken as jest.Mock).mockResolvedValue(
      true,
    );
    (BookingCreateSchema.safeParse as jest.Mock).mockReturnValue({
      success: true,
      data: {
        organizationId: "org-1",
        customerName: "Test",
        customerPhone: "+966501234567",
        appointmentDate: "2026-03-02T10:00:00Z",
        duration: 30,
        language: "en",
      },
    });
    (requireFeatureAccess as jest.Mock).mockResolvedValue(undefined);
    (isSlotAvailable as jest.Mock).mockResolvedValue(true);
    (prisma.organizations.findUnique as jest.Mock).mockRejectedValue(
      new Error("DB error"),
    );

    const response = await bookingModule.POST(
      mockRequest("Bearer valid-token"),
    );
    expect(response.status).toBe(500);
  });
});
