import { api } from './api';
import { API_URL } from '../utils/config';
import type {
  Uebung,
  UebungWithAttendance,
  UebungListItem,
  MemberParticipationStats,
  CreateUebungData,
  UpdateUebungData,
} from '../types/training.types';

// ---------------------------------------------------------------------------
// Response shapes from the backend
// ---------------------------------------------------------------------------
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

// ---------------------------------------------------------------------------
// Helper: iCal subscribe URL
// ---------------------------------------------------------------------------
export function buildIcalUrl(token: string): string {
  const base = API_URL.replace(/\/$/, '');
  return `${base}/api/training/calendar.ics?token=${token}`;
}

// ---------------------------------------------------------------------------
// Training API service
// ---------------------------------------------------------------------------
export const trainingApi = {
  // -------------------------------------------------------------------------
  // Event listing
  // -------------------------------------------------------------------------

  /** Upcoming events (dashboard widget, list view) */
  getUpcoming(limit = 10): Promise<UebungListItem[]> {
    return api
      .get<ApiResponse<UebungListItem[]>>('/api/training', { params: { limit } })
      .then((r) => r.data.data);
  },

  /** Events in a date range for the month calendar view */
  getCalendarRange(from: Date, to: Date): Promise<UebungListItem[]> {
    return api
      .get<ApiResponse<UebungListItem[]>>('/api/training/calendar', {
        params: {
          from: from.toISOString(),
          to: to.toISOString(),
        },
      })
      .then((r) => r.data.data);
  },

  /** Full event detail with attendance data */
  getById(id: string): Promise<UebungWithAttendance> {
    return api
      .get<ApiResponse<UebungWithAttendance>>(`/api/training/${id}`)
      .then((r) => r.data.data);
  },

  // -------------------------------------------------------------------------
  // CRUD
  // -------------------------------------------------------------------------

  createEvent(data: CreateUebungData): Promise<Uebung> {
    return api
      .post<ApiResponse<Uebung>>('/api/training', data)
      .then((r) => r.data.data);
  },

  updateEvent(id: string, data: Partial<UpdateUebungData>): Promise<Uebung> {
    return api
      .patch<ApiResponse<Uebung>>(`/api/training/${id}`, data)
      .then((r) => r.data.data);
  },

  cancelEvent(id: string, absage_grund: string): Promise<void> {
    return api
      .delete(`/api/training/${id}`, { data: { absage_grund } })
      .then(() => undefined);
  },

  // -------------------------------------------------------------------------
  // Attendance / RSVP
  // -------------------------------------------------------------------------

  /** Member updates own RSVP */
  updateRsvp(
    uebungId: string,
    status: 'zugesagt' | 'abgesagt',
    bemerkung?: string
  ): Promise<void> {
    return api
      .patch(`/api/training/${uebungId}/attendance`, { status, bemerkung })
      .then(() => undefined);
  },

  /** Gruppenführer bulk-marks attendance */
  markAttendance(uebungId: string, userIds: string[]): Promise<void> {
    return api
      .post(`/api/training/${uebungId}/attendance/mark`, { userIds })
      .then(() => undefined);
  },

  // -------------------------------------------------------------------------
  // Stats
  // -------------------------------------------------------------------------

  getMemberStats(year?: number): Promise<MemberParticipationStats[]> {
    return api
      .get<ApiResponse<MemberParticipationStats[]>>('/api/training/stats', {
        params: { year: year ?? new Date().getFullYear() },
      })
      .then((r) => r.data.data);
  },

  // -------------------------------------------------------------------------
  // iCal
  // -------------------------------------------------------------------------

  /** Get the user's personal calendar subscribe URL */
  getCalendarToken(): Promise<{ token: string; subscribeUrl: string; instructions: string }> {
    return api
      .get<ApiResponse<{ token: string; subscribeUrl: string; instructions: string }>>(
        '/api/training/calendar-token'
      )
      .then((r) => r.data.data);
  },
};
