"use server";

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

export async function getMedicalRecord(patientId: string) {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("medical_records")
    .select("*")
    .eq("patient_id", patientId)
    .single();
  if (error && error.code !== "PGRST116") throw error;
  return data;
}

export async function upsertMedicalRecord(patientId: string, record: any) {
  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("medical_records").upsert({
    patient_id: patientId,
    clinic_id: profile.clinic_id,
    ...record,
    updated_at: new Date().toISOString(),
  }, { onConflict: "patient_id" });

  if (error) throw error;
  revalidatePath(`/medical-records/${patientId}`);
}

export async function getConsultations(patientId: string) {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("consultation_notes")
    .select("*, doctor:users(id, full_name, specialty)")
    .eq("patient_id", patientId)
    .order("created_at", { ascending: false });
  if (error) throw error;
  return data;
}

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

export async function createConsultation(data: {
  patient_id: string;
  appointment_id?: string;
  subjective?: string;
  objective?: string;
  assessment?: string;
  plan?: string;
  vital_signs?: any;
  diagnoses?: any[];
}) {
  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("consultation_notes").insert({
    clinic_id: profile.clinic_id,
    doctor_id: user.id,
    ...data,
  });
  if (error) throw error;
  revalidatePath(`/medical-records/${data.patient_id}`);
}

export async function signConsultation(id: string) {
  const supabase = await createClient();
  const { error } = await supabase.from("consultation_notes").update({
    is_signed: true,
    signed_at: new Date().toISOString(),
  }).eq("id", id);
  if (error) throw error;
}

export async function createPrescription(data: {
  consultation_id: string;
  patient_id: string;
  items: any[];
  pharmacy_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("prescriptions").insert({
    clinic_id: profile.clinic_id,
    doctor_id: user.id,
    ...data,
  });
  if (error) throw error;
}
