"use server";

import { createClient } from "@/lib/supabase/server";
import { revalidatePath } from "next/cache";

export async function getPatients(search?: string) {
  const supabase = await createClient();
  let query = supabase
    .from("patients")
    .select("*")
    .eq("is_active", true)
    .order("created_at", { ascending: false });

  if (search) {
    query = query.or(
      `first_name.ilike.%${search}%,last_name.ilike.%${search}%,phone.ilike.%${search}%,curp.ilike.%${search}%`
    );
  }

  const { data, error } = await query;
  if (error) throw error;
  return data;
}

export async function getPatient(id: string) {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("patients")
    .select("*")
    .eq("id", id)
    .single();
  if (error) throw error;
  return data;
}

export async function createPatient(formData: FormData) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");

  const { data: profile } = await supabase
    .from("users")
    .select("clinic_id")
    .eq("id", user.id)
    .single();
  if (!profile) throw new Error("Perfil no encontrado");

  const patient = {
    clinic_id: profile.clinic_id,
    first_name: formData.get("first_name") as string,
    last_name: formData.get("last_name") as string,
    date_of_birth: (formData.get("date_of_birth") as string) || null,
    gender: (formData.get("gender") as string) || null,
    curp: (formData.get("curp") as string) || null,
    phone: (formData.get("phone") as string) || null,
    email: (formData.get("email") as string) || null,
    blood_type: (formData.get("blood_type") as string) || null,
    notes: (formData.get("notes") as string) || null,
    source: (formData.get("source") as string) || null,
  };

  const { error } = await supabase.from("patients").insert(patient);
  if (error) throw error;
  revalidatePath("/patients");
}

export async function updatePatient(id: string, formData: FormData) {
  const supabase = await createClient();

  const updates: Record<string, unknown> = {};
  const fields = [
    "first_name",
    "last_name",
    "date_of_birth",
    "gender",
    "curp",
    "phone",
    "email",
    "blood_type",
    "notes",
    "source",
  ];
  for (const field of fields) {
    const value = formData.get(field) as string;
    updates[field] = value || null;
  }

  const { error } = await supabase
    .from("patients")
    .update(updates)
    .eq("id", id);
  if (error) throw error;
  revalidatePath("/patients");
  revalidatePath(`/patients/${id}`);
}
