/**
 * Tests for Appointments by Phone API
 *
 * Tests the /api/appointments/by-phone endpoint
 */

import { NextRequest } from "next/server";

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

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

// Route not yet implemented - imports skipped
let POST: any;
import { prisma } from "@/lib/db";

// Voice agent routes not yet implemented
describe.skip("POST /api/appointments/by-phone", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    jest.useFakeTimers();
    jest.setSystemTime(new Date("2024-01-15T10:00:00Z"));
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  const createRequest = (body: Record<string, unknown>) => {
    return new NextRequest("http://localhost/api/appointments/by-phone", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });
  };

  it("should return 400 if phone_number is missing", async () => {
    const request = createRequest({});

    const response = await POST(request);

    expect(response.status).toBe(400);
    const data = await response.json();
    expect(data.error).toBe("Invalid query parameters");
  });

  it("should return empty array when no appointments found", async () => {
    (prisma.bookings.findMany as jest.Mock).mockResolvedValue([]);

    const request = createRequest({
      phone_number: "+1234567890",
    });

    const response = await POST(request);

    expect(response.status).toBe(200);
    const data = await response.json();

    expect(data.success).toBe(true);
    expect(data.appointments).toEqual([]);
    expect(data.message).toBe("No appointments found for this phone number.");
  });

  it("should return upcoming appointments", async () => {
    (prisma.bookings.findMany as jest.Mock).mockResolvedValue([
      {
        id: "booking-1",
        customerName: "John Doe",
        customerPhone: "+1234567890",
        service: "Dental Checkup",
        appointmentDate: new Date("2024-01-20"),
        appointmentTime: "10:00",
        staffMember: "Dr. Smith",
        status: "confirmed",
      },
      {
        id: "booking-2",
        customerName: "John Doe",
        customerPhone: "+1234567890",
        service: "Follow-up",
        appointmentDate: new Date("2024-01-25"),
        appointmentTime: "14:00",
        staffMember: null,
        status: "pending",
      },
    ]);

    const request = createRequest({
      phone_number: "+1234567890",
    });

    const response = await POST(request);

    expect(response.status).toBe(200);
    const data = await response.json();

    expect(data.success).toBe(true);
    expect(data.appointments).toHaveLength(2);
    expect(data.upcoming_count).toBe(2);
    expect(data.past_count).toBe(0);

    // Verify first appointment
    expect(data.appointments[0].service).toBe("Dental Checkup");
    expect(data.appointments[0].doctor).toBe("Dr. Smith");
    expect(data.appointments[0].is_past).toBe(false);

    // Verify second appointment has default doctor
    expect(data.appointments[1].doctor).toBe("First available");
  });

  it("should include past appointments when requested", async () => {
    (prisma.bookings.findMany as jest.Mock).mockResolvedValue([
      {
        id: "booking-1",
        customerName: "John Doe",
        customerPhone: "+1234567890",
        service: "Past Checkup",
        appointmentDate: new Date("2024-01-10"), // Past date
        appointmentTime: "10:00",
        staffMember: "Dr. Smith",
        status: "completed",
      },
      {
        id: "booking-2",
        customerName: "John Doe",
        customerPhone: "+1234567890",
        service: "Future Checkup",
        appointmentDate: new Date("2024-01-20"),
        appointmentTime: "14:00",
        staffMember: "Dr. Jones",
        status: "confirmed",
      },
    ]);

    const request = createRequest({
      phone_number: "+1234567890",
      include_past: true,
    });

    const response = await POST(request);

    expect(response.status).toBe(200);
    const data = await response.json();

    expect(data.success).toBe(true);
    expect(data.appointments).toHaveLength(2);
    expect(data.upcoming_count).toBe(1);
    expect(data.past_count).toBe(1);

    // Verify past appointment is marked
    const pastAppointment = data.appointments.find(
      (a: { service: string }) => a.service === "Past Checkup",
    );
    expect(pastAppointment.is_past).toBe(true);
  });

  it("should normalize phone number for search", async () => {
    (prisma.bookings.findMany as jest.Mock).mockResolvedValue([]);

    const request = createRequest({
      phone_number: "+1 (234) 567-8900",
    });

    await POST(request);

    // Verify search pattern uses normalized number
    expect(prisma.bookings.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.objectContaining({
          customerPhone: expect.objectContaining({
            contains: "2345678900", // Last 10 digits
          }),
        }),
      }),
    );
  });

  it("should generate human-readable descriptions", async () => {
    (prisma.bookings.findMany as jest.Mock).mockResolvedValue([
      {
        id: "booking-1",
        customerName: "John Doe",
        customerPhone: "+1234567890",
        service: "Dental Checkup",
        appointmentDate: new Date("2024-01-20"),
        appointmentTime: "10:00",
        staffMember: "Dr. Smith",
        status: "confirmed",
      },
    ]);

    const request = createRequest({
      phone_number: "+1234567890",
    });

    const response = await POST(request);

    expect(response.status).toBe(200);
    const data = await response.json();

    // Verify description is generated
    expect(data.appointments[0].description).toContain("Dental Checkup");
    expect(data.appointments[0].description).toContain("10:00");
    expect(data.appointments[0].description).toContain("Dr. Smith");
  });
});
