import { apiClient } from './client';

export interface Tenant {
  id: string;
  nombre: string;
  rfc: string;
  plan: string;
  databaseName: string;
  createdAt: string;
  _count?: {
    /** Memberships activos (matches el `_count.memberships` que retorna `getAllTenants`). */
    memberships: number;
  };
}

export interface CreateTenantData {
  nombre: string;
  rfc: string;
  plan?: 'starter' | 'business' | 'business_ia' | 'enterprise' | 'custom';
  cfdiLimit?: number;
  usersLimit?: number;
  adminEmail: string;
  adminNombre: string;
  amount?: number;
}

export async function getTenants(): Promise<Tenant[]> {
  const response = await apiClient.get<Tenant[]>('/tenants');
  return response.data;
}

export async function getTenant(id: string): Promise<Tenant> {
  const response = await apiClient.get<Tenant>(`/tenants/${id}`);
  return response.data;
}

export async function createTenant(data: CreateTenantData): Promise<Tenant> {
  const response = await apiClient.post<Tenant>('/tenants', data);
  return response.data;
}

export interface UpdateTenantData {
  nombre?: string;
  rfc?: string;
  plan?: 'starter' | 'business' | 'business_ia' | 'enterprise' | 'custom';
  cfdiLimit?: number;
  usersLimit?: number;
  active?: boolean;
}

export async function updateTenant(id: string, data: UpdateTenantData): Promise<Tenant> {
  const response = await apiClient.put<Tenant>(`/tenants/${id}`, data);
  return response.data;
}

export async function deleteTenant(id: string): Promise<void> {
  await apiClient.delete(`/tenants/${id}`);
}

// ============================================================================
// Self-serve multi-tenant (memberships del caller)
// ============================================================================

export interface MyTenantDetailed {
  tenantId: string;
  nombre: string;
  rfc: string;
  plan: string;
  role: string;
  isOwner: boolean;
  trialEndsAt: string | null;
  subscription: {
    status: string;
    plan: string;
    amount: number;
    frequency: string;
    currentPeriodEnd: string | null;
    pendingPlan: string | null;
    pendingEffectiveAt: string | null;
  } | null;
}

export async function getMyTenants(): Promise<MyTenantDetailed[]> {
  const response = await apiClient.get<MyTenantDetailed[]>('/tenants/mine');
  return response.data;
}

export interface AddMyTenantData {
  nombre: string;
  rfc: string;
  plan?: 'starter' | 'business' | 'business_ia' | 'enterprise';
}

export async function addMyTenant(data: AddMyTenantData): Promise<{ tenant: Tenant }> {
  const response = await apiClient.post<{ tenant: Tenant }>('/tenants/mine', data);
  return response.data;
}
