import { apiClient } from './client';
import type { AppointmentColumnProvider, AppointmentRecord } from '@/types/appointment';
import { getClientTimeZone } from '@/lib/i18n/clientTimeZone';
import { toDateInputValue } from '@/components/appointments/appointmentTime';

export interface CreateAppointmentBody {
  patientId: string;
  providerUserId: string;
  startAt: string;
  endAt: string;
  purpose: string;
}

export type UpdateAppointmentBody = Partial<CreateAppointmentBody>;

export const appointmentsApi = {
  columnProviders: async (
    scheduleDate?: Date,
  ): Promise<{ success: boolean; data: AppointmentColumnProvider[] }> => {
    const params = scheduleDate ? { date: toDateInputValue(scheduleDate) } : undefined;
    const response = await apiClient.get('/appointments/column-providers', { params });
    return response.data;
  },

  list: async (params: { from: string; to: string }): Promise<{ success: boolean; data: AppointmentRecord[] }> => {
    const response = await apiClient.get('/appointments', { params });
    return response.data;
  },

  create: async (body: CreateAppointmentBody): Promise<{ success: boolean; data: AppointmentRecord }> => {
    const response = await apiClient.post('/appointments', {
      ...body,
      timeZone: getClientTimeZone(),
    });
    return response.data;
  },

  update: async (
    id: string,
    body: UpdateAppointmentBody,
  ): Promise<{ success: boolean; data: AppointmentRecord }> => {
    const response = await apiClient.patch(`/appointments/${id}`, {
      ...body,
      timeZone: getClientTimeZone(),
    });
    return response.data;
  },

  remove: async (id: string): Promise<{ success: boolean }> => {
    const response = await apiClient.delete(`/appointments/${id}`);
    return response.data;
  },
};
