"use server";

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

export async function getAppointments(startDate?: string, endDate?: string, doctorId?: string) {
  const supabase = await createClient();
  let query = supabase
    .from("appointments")
    .select("*, patient:patients(id, first_name, last_name, phone), doctor:users(id, full_name, color, specialty)")
    .order("starts_at", { ascending: true });

  if (startDate) query = query.gte("starts_at", startDate);
  if (endDate) query = query.lte("starts_at", endDate);
  if (doctorId) query = query.eq("doctor_id", doctorId);

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

export async function getAppointment(id: string) {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("appointments")
    .select("*, patient:patients(id, first_name, last_name, phone, email), doctor:users(id, full_name, specialty)")
    .eq("id", id)
    .single();
  if (error) throw error;
  return data;
}

export async function createAppointment(data: {
  patient_id: string;
  doctor_id: string;
  starts_at: string;
  ends_at: string;
  type: string;
  reason?: string;
  notes?: string;
}) {
  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 { error } = await supabase.from("appointments").insert({
    clinic_id: profile.clinic_id,
    patient_id: data.patient_id,
    doctor_id: data.doctor_id,
    starts_at: data.starts_at,
    ends_at: data.ends_at,
    type: data.type,
    reason: data.reason || null,
    notes: data.notes || null,
    status: "scheduled",
    created_by: user.id,
  });
  if (error) throw error;
  revalidatePath("/appointments");
}

export async function updateAppointmentStatus(id: string, status: string) {
  const supabase = await createClient();
  const { error } = await supabase.from("appointments").update({ status }).eq("id", id);
  if (error) throw error;
  revalidatePath("/appointments");
}

export async function rescheduleAppointment(id: string, starts_at: string, ends_at: string) {
  const supabase = await createClient();
  const { error } = await supabase.from("appointments").update({ starts_at, ends_at }).eq("id", id);
  if (error) throw error;
  revalidatePath("/appointments");
}

export async function getDoctors() {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("users")
    .select("id, full_name, specialty, color")
    .eq("role", "doctor")
    .eq("is_active", true)
    .order("full_name");
  if (error) throw error;
  return data;
}

export async function getPatientsList() {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("patients")
    .select("id, first_name, last_name, phone")
    .eq("is_active", true)
    .order("last_name")
    .limit(200);
  if (error) throw error;
  return data;
}
