import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";
import { checkRateLimit } from "@/lib/rate-limiter";
import { patientSchema } from "@/lib/validations";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Validate phone format
    if (!body.phone) {
      return NextResponse.json({ error: "Phone number is required" }, { status: 400 });
    }

    const ip =
      request.ip ||
      request.headers.get("x-forwarded-for")?.split(",")[0] ||
      request.headers.get("x-real-ip") ||
      "unknown";

    // Check rate limit by IP
    const ipLimit = await checkRateLimit(ip, "ip");
    if (!ipLimit.success) {
      return NextResponse.json(
        {
          error: "Too many requests",
          limit: ipLimit.limit,
          remaining: ipLimit.remaining,
          resetTime: ipLimit.resetTime,
        },
        {
          status: 429,
          headers: {
            "X-RateLimit-Limit": ipLimit.limit.toString(),
            "X-RateLimit-Remaining": ipLimit.remaining.toString(),
            "X-RateLimit-Reset": ipLimit.resetTime.toISOString(),
          },
        }
      );
    }

    // Check rate limit by phone
    const phoneLimit = await checkRateLimit(body.phone, "phone");
    if (!phoneLimit.success) {
      return NextResponse.json(
        {
          error: "Too many requests for this phone number",
          limit: phoneLimit.limit,
          remaining: phoneLimit.remaining,
          resetTime: phoneLimit.resetTime,
        },
        {
          status: 429,
          headers: {
            "X-RateLimit-Limit": phoneLimit.limit.toString(),
            "X-RateLimit-Remaining": phoneLimit.remaining.toString(),
            "X-RateLimit-Reset": phoneLimit.resetTime.toISOString(),
          },
        }
      );
    }

    // Search for patient by phone
    const patient = await prisma.patient.findUnique({
      where: { phone: body.phone },
      select: {
        phone: true,
        name: true,
        status: true,
        createdAt: true,
      },
    });

    // Rate limit headers for successful response
    const headers = {
      "X-RateLimit-Limit": phoneLimit.limit.toString(),
      "X-RateLimit-Remaining": phoneLimit.remaining.toString(),
      "X-RateLimit-Reset": phoneLimit.resetTime.toISOString(),
    };

    if (patient) {
      // Patient exists
      return NextResponse.json(
        {
          exists: true,
          patient: {
            phone: patient.phone,
            name: patient.name,
            status: patient.status,
          },
          message: "Patient found",
        },
        { headers }
      );
    } else {
      // Patient doesn't exist
      return NextResponse.json(
        {
          exists: false,
          message: "Patient not found, please register",
        },
        { headers }
      );
    }
  } catch (error) {
    console.error("Patient search error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
