import { http } from './http';
import { SaasTenantDataSource, SaasTenant, TenantDomain, TenantUser, TenantSettings } from './saasTenantTypes';

const API_BASE = '/api/saas-tenant';

export class SaasTenantDataSourceImpl implements SaasTenantDataSource {
  async list(filters?: {
    status?: string;
    plan?: string;
    type?: string;
  }): Promise<SaasTenant[]> {
    const params = new URLSearchParams();
    if (filters?.status) params.append('status', filters.status);
    if (filters?.plan) params.append('plan', filters.plan);
    if (filters?.type) params.append('type', filters.type);
    
    const response = await http.get(`${API_BASE}/tenants?${params.toString()}`);
    return response.data;
  }
  
  async get(tenantId: string): Promise<SaasTenant | null> {
    try {
      const response = await http.get(`${API_BASE}/tenants/${tenantId}`);
      return response.data;
    } catch (error: any) {
      if (error.response?.status === 404) return null;
      throw error;
    }
  }
  
  async create(data: {
    code: string;
    name: string;
    type?: 'SAAS' | 'ENTERPRISE' | 'TRIAL';
    plan?: 'BASIC' | 'PRO' | 'ENTERPRISE';
    maxUsers?: number;
    maxShops?: number;
    storageQuota?: number;
    features?: string[];
    config?: Record<string, any>;
    expiresAt?: Date;
  }): Promise<SaasTenant> {
    const response = await http.post(`${API_BASE}/tenants`, data);
    return response.data;
  }
  
  async update(tenantId: string, data: Partial<SaasTenant>): Promise<SaasTenant> {
    const response = await http.put(`${API_BASE}/tenants/${tenantId}`, data);
    return response.data;
  }
  
  async delete(tenantId: string): Promise<void> {
    await http.delete(`${API_BASE}/tenants/${tenantId}`);
  }
  
  async updateStatus(tenantId: string, status: 'ACTIVE' | 'SUSPENDED' | 'CANCELED'): Promise<SaasTenant> {
    const response = await http.put(`${API_BASE}/tenants/${tenantId}/status`, { status });
    return response.data;
  }
  
  async getDomains(tenantId: string): Promise<TenantDomain[]> {
    const response = await http.get(`${API_BASE}/tenants/${tenantId}/domains`);
    return response.data;
  }
  
  async addDomain(tenantId: string, domain: string, type?: 'SUBDOMAIN' | 'CUSTOM_DOMAIN'): Promise<TenantDomain> {
    const response = await http.post(`${API_BASE}/tenants/${tenantId}/domains`, { domain, type });
    return response.data;
  }
  
  async verifyDomain(domainId: string): Promise<TenantDomain> {
    const response = await http.post(`${API_BASE}/domains/${domainId}/verify`);
    return response.data;
  }
  
  async setPrimaryDomain(domainId: string): Promise<void> {
    await http.post(`${API_BASE}/domains/${domainId}/primary`);
  }
  
  async deleteDomain(domainId: string): Promise<void> {
    await http.delete(`${API_BASE}/domains/${domainId}`);
  }
  
  async getUsers(tenantId: string): Promise<TenantUser[]> {
    const response = await http.get(`${API_BASE}/tenants/${tenantId}/users`);
    return response.data;
  }
  
  async addUser(tenantId: string, userId: string, role?: 'ADMIN' | 'MANAGER' | 'OPERATOR' | 'VIEWER', permissions?: string[]): Promise<TenantUser> {
    const response = await http.post(`${API_BASE}/tenants/${tenantId}/users`, { userId, role, permissions });
    return response.data;
  }
  
  async updateUserRole(tenantId: string, userId: string, role: 'ADMIN' | 'MANAGER' | 'OPERATOR' | 'VIEWER', permissions?: string[]): Promise<TenantUser> {
    const response = await http.put(`${API_BASE}/tenants/${tenantId}/users/${userId}/role`, { role, permissions });
    return response.data;
  }
  
  async removeUser(tenantId: string, userId: string): Promise<void> {
    await http.delete(`${API_BASE}/tenants/${tenantId}/users/${userId}`);
  }
  
  async getUserTenants(userId: string): Promise<Array<{ tenant: SaasTenant; user: TenantUser }>> {
    const response = await http.get(`${API_BASE}/users/${userId}/tenants`);
    return response.data;
  }
  
  async getSettings(tenantId: string, category?: string): Promise<TenantSettings> {
    const params = category ? `?category=${category}` : '';
    const response = await http.get(`${API_BASE}/tenants/${tenantId}/settings${params}`);
    return response.data;
  }
  
  async getSetting(tenantId: string, key: string): Promise<string | null> {
    try {
      const response = await http.get(`${API_BASE}/tenants/${tenantId}/settings/${key}`);
      return response.data;
    } catch (error: any) {
      if (error.response?.status === 404) return null;
      throw error;
    }
  }
  
  async setSetting(tenantId: string, key: string, value: string, category?: string): Promise<void> {
    await http.put(`${API_BASE}/tenants/${tenantId}/settings/${key}`, { value, category });
  }
  
  async getCurrentTenant(): Promise<SaasTenant | null> {
    try {
      const response = await http.get(`${API_BASE}/current`);
      return response.data;
    } catch (error: any) {
      if (error.response?.status === 404) return null;
      throw error;
    }
  }
  
  async getStats(): Promise<{
    totalTenants: number;
    activeTenants: number;
    suspendedTenants: number;
    trialTenants: number;
    totalUsers: number;
    totalShops: number;
    totalDomains: number;
    storageUsed: number;
    storageTotal: number;
  }> {
    const response = await http.get(`${API_BASE}/stats`);
    return response.data;
  }
  
  async getUsage(tenantId: string): Promise<{
    userId: number;
    shopId: number;
    storageUsed: number;
    apiCalls: number;
    lastActive: Date;
  }> {
    const response = await http.get(`${API_BASE}/tenants/${tenantId}/usage`);
    return response.data;
  }
  
  async getOperationLogs(tenantId: string): Promise<Array<{
    id: string;
    tenantId: string;
    tenantName: string;
    operation: string;
    operator: string;
    timestamp: Date;
    details: string;
  }>> {
    const response = await http.get(`${API_BASE}/tenants/${tenantId}/logs`);
    return response.data;
  }
  
  async exportTenants(tenants: SaasTenant[]): Promise<void> {
    await http.post(`${API_BASE}/tenants/export`, { tenants });
  }
  
  async suspend(tenantId: string, reason?: string): Promise<void> {
    await http.post(`${API_BASE}/tenants/${tenantId}/suspend`, { reason });
  }
  
  async activate(tenantId: string): Promise<void> {
    await http.post(`${API_BASE}/tenants/${tenantId}/activate`);
  }
}

export const saasTenantDataSource = new SaasTenantDataSourceImpl();
