/**
 * Serviço de Agendamentos
 */

import { apiClient } from "../api/client";
import type {
  Appointment,
  CreateAppointmentInput,
  UpdateAppointmentInput,
  AppointmentFilters,
  GetAvailableSlotsInput,
  GetAvailableSlotsResponse,
} from "./types";

class AppointmentService {
  private readonly basePath = "/appointments";

  /**
   * Busca horários disponíveis de um médico
   */
  async getAvailableSlots(
    data: GetAvailableSlotsInput
  ): Promise<GetAvailableSlotsResponse> {
    const response = await apiClient.post<GetAvailableSlotsResponse>(
      "/get-available-slots",
      data
    );
    return response.data;
  }

  /**
   * Lista agendamentos com filtros opcionais
   */
  async list(filters?: AppointmentFilters): Promise<Appointment[]> {
    const params: Record<string, string> = {};

    if (filters?.doctor_id) {
      params["doctor_id"] = `eq.${filters.doctor_id}`;
    }

    if (filters?.patient_id) {
      params["patient_id"] = `eq.${filters.patient_id}`;
    }

    if (filters?.status) {
      params["status"] = `eq.${filters.status}`;
    }

    if (filters?.scheduled_at) {
      params["scheduled_at"] = filters.scheduled_at;
    }

    if (filters?.limit) {
      params["limit"] = filters.limit.toString();
    }

    if (filters?.offset) {
      params["offset"] = filters.offset.toString();
    }

    if (filters?.order) {
      params["order"] = filters.order;
    }

    const response = await apiClient.get<Appointment[]>(this.basePath, {
      params,
    });
    return response.data;
  }

  /**
   * Busca agendamento por ID
   */
  async getById(id: string): Promise<Appointment> {
    const response = await apiClient.get<Appointment[]>(
      `${this.basePath}?id=eq.${id}`
    );
    if (response.data && response.data.length > 0) {
      return response.data[0];
    }
    throw new Error("Agendamento não encontrado");
  }

  /**
   * Cria novo agendamento
   * Nota: order_number é gerado automaticamente (APT-YYYY-NNNN)
   */
  async create(data: CreateAppointmentInput): Promise<Appointment> {
    const response = await apiClient.post<Appointment>(this.basePath, data);
    return response.data;
  }

  /**
   * Atualiza agendamento existente
   */
  async update(id: string, data: UpdateAppointmentInput): Promise<Appointment> {
    const response = await apiClient.patch<Appointment[]>(
      `${this.basePath}?id=eq.${id}`,
      data
    );
    if (response.data && response.data.length > 0) {
      return response.data[0];
    }
    throw new Error("Agendamento não encontrado");
  }

  /**
   * Deleta agendamento
   */
  async delete(id: string): Promise<void> {
    await apiClient.delete(`${this.basePath}?id=eq.${id}`);
  }
}

export const appointmentService = new AppointmentService();
