import api from '../../../shared/utils/api';

// ==================== DTOs ====================

export type TenantStatus = 'ACTIVE' | 'SUSPENDED' | 'ARCHIVED';
export type TenantPlan = 'FREE' | 'STANDARD' | 'ENTERPRISE';

export interface TenantConfigData {
  branding?: {
    logoUrl?: string;
    primaryColor?: string;
    companyName?: string;
    favicon?: string;
  };
  ai?: {
    systemPrompt?: string;
    model?: string;
    temperature?: number;
    maxTokens?: number;
  };
  features?: {
    enableFileUpload?: boolean;
    enableKnowledgeBase?: boolean;
    enablePayments?: boolean;
    enableUserMemory?: boolean;
    enableAnalytics?: boolean;
  };
}

export interface TenantDto {
  id: string;
  name: string;
  slug: string;
  status: TenantStatus;
  plan: TenantPlan;
  maxUsers: number;
  maxConversationsPerMonth: number;
  maxStorageMb: number;
  currentUserCount: number;
  currentConversationCount: number;
  currentStorageBytes: number;
  config: TenantConfigData;
  billingEmail: string | null;
  billingName: string | null;
  billingPhone: string | null;
  createdAt: string;
  updatedAt: string;
  suspendedAt: string | null;
}

export interface TenantAdminDto {
  id: string;
  tenantId: string;
  username: string;
  name: string;
  email?: string;
  phone?: string;
  role: string;
  isActive: boolean;
  lastLoginAt?: string;
  createdAt: string;
}

export interface PaginatedTenants {
  data: TenantDto[];
  total: number;
}

export interface TenantQueryParams {
  status?: TenantStatus;
  plan?: TenantPlan;
  page?: number;
  limit?: number;
}

export interface GlobalStats {
  totalTenants: number;
  activeTenants: number;
  suspendedTenants: number;
  totalUsers: number;
  totalConversations: number;
  totalStorage: number;
}

export interface CreateTenantDto {
  name: string;
  slug: string;
  plan?: TenantPlan;
  maxUsers?: number;
  maxConversationsPerMonth?: number;
  maxStorageMb?: number;
  billingEmail?: string;
  billingName?: string;
  billingPhone?: string;
  config?: TenantConfigData;
}

export interface UpdateTenantDto {
  name?: string;
  plan?: TenantPlan;
  maxUsers?: number;
  maxConversationsPerMonth?: number;
  maxStorageMb?: number;
  billingEmail?: string;
  billingName?: string;
  billingPhone?: string;
  config?: TenantConfigData;
}

export interface CreateTenantAdminDto {
  username: string;
  password: string;
  name: string;
  email?: string;
  phone?: string;
  role?: 'ADMIN' | 'OPERATOR' | 'VIEWER';
}

// ==================== API ====================

// Note: Super admin API uses /evolution/super-admin/* through Kong gateway
const SUPER_ADMIN_BASE = '/evolution/super-admin';

export const tenantsApi = {
  // Get global statistics
  getGlobalStats: async (): Promise<GlobalStats> => {
    const response = await api.get(`${SUPER_ADMIN_BASE}/tenants/stats`);
    return response.data.data || response.data;
  },

  // List tenants with pagination
  listTenants: async (params: TenantQueryParams): Promise<PaginatedTenants> => {
    const response = await api.get(`${SUPER_ADMIN_BASE}/tenants`, { params });
    return response.data.data || response.data;
  },

  // Get tenant detail
  getTenantDetail: async (id: string): Promise<TenantDto> => {
    const response = await api.get(`${SUPER_ADMIN_BASE}/tenants/${id}`);
    return response.data.data || response.data;
  },

  // Create tenant
  createTenant: async (dto: CreateTenantDto): Promise<TenantDto> => {
    const response = await api.post(`${SUPER_ADMIN_BASE}/tenants`, dto);
    return response.data.data || response.data;
  },

  // Update tenant
  updateTenant: async (id: string, dto: UpdateTenantDto): Promise<TenantDto> => {
    const response = await api.put(`${SUPER_ADMIN_BASE}/tenants/${id}`, dto);
    return response.data.data || response.data;
  },

  // Suspend tenant
  suspendTenant: async (id: string, reason?: string): Promise<TenantDto> => {
    const response = await api.post(`${SUPER_ADMIN_BASE}/tenants/${id}/suspend`, { reason });
    return response.data.data || response.data;
  },

  // Activate tenant
  activateTenant: async (id: string): Promise<TenantDto> => {
    const response = await api.post(`${SUPER_ADMIN_BASE}/tenants/${id}/activate`);
    return response.data.data || response.data;
  },

  // Archive tenant
  archiveTenant: async (id: string): Promise<TenantDto> => {
    const response = await api.post(`${SUPER_ADMIN_BASE}/tenants/${id}/archive`);
    return response.data.data || response.data;
  },

  // Get tenant admins
  getTenantAdmins: async (tenantId: string): Promise<TenantAdminDto[]> => {
    const response = await api.get(`${SUPER_ADMIN_BASE}/tenants/${tenantId}/admins`);
    return response.data.data || response.data;
  },

  // Create tenant admin
  createTenantAdmin: async (tenantId: string, dto: CreateTenantAdminDto): Promise<TenantAdminDto> => {
    const response = await api.post(`${SUPER_ADMIN_BASE}/tenants/${tenantId}/admins`, dto);
    return response.data.data || response.data;
  },
};
