import { apiClient } from './client';

export interface TrialInvitation {
  id: string;
  tenantId: string;
  plan: string;
  durationDays: number;
  status: string;
  token: string;
  sentAt: string;
  expiresAt: string;
  acceptedAt: string | null;
  tenant: {
    nombre: string;
    rfc: string;
  } | null;
}

export async function getPendingInvitation(): Promise<TrialInvitation | null> {
  try {
    const response = await apiClient.get<TrialInvitation | null>('/invitations/trial/pending');
    return response.data;
  } catch (error: any) {
    if (error?.response?.status === 404) return null;
    throw error;
  }
}

export async function getInvitationByToken(token: string): Promise<TrialInvitation | null> {
  try {
    const response = await apiClient.get<TrialInvitation | null>(`/invitations/trial/token/${token}`);
    return response.data;
  } catch (error: any) {
    if (error?.response?.status === 404) return null;
    throw error;
  }
}

export async function acceptInvitation(token: string): Promise<{
  success: boolean;
  trialEndsAt: string;
  plan: string;
  durationDays: number;
}> {
  const response = await apiClient.post(`/invitations/trial/${token}/accept`);
  return response.data;
}

// Admin endpoints
export async function getAllInvitations(filters?: { tenantId?: string; status?: string }): Promise<TrialInvitation[]> {
  const params = new URLSearchParams();
  if (filters?.tenantId) params.append('tenantId', filters.tenantId);
  if (filters?.status) params.append('status', filters.status);
  const response = await apiClient.get<TrialInvitation[]>(`/invitations/trial?${params.toString()}`);
  return response.data;
}

export async function createInvitation(data: {
  tenantId: string;
  plan?: string;
  durationDays: number;
}): Promise<TrialInvitation> {
  const response = await apiClient.post<TrialInvitation>('/invitations/trial', data);
  return response.data;
}

export async function cancelInvitation(id: string): Promise<TrialInvitation> {
  const response = await apiClient.post<TrialInvitation>(`/invitations/trial/${id}/cancel`);
  return response.data;
}
