import apiClient from '../../../shared/services/apiClient';

export interface SecurityEvent {
  id: number;
  user_id?: number;
  event_type: string;
  severity: string;
  ip_address?: string;
  user_agent?: string;
  request_path?: string;
  request_method?: string;
  description?: string;
  details?: Record<string, unknown>;
  resolved: boolean;
  resolved_at?: string;
  resolved_by?: number;
  resolution_notes?: string;
  created_at: string;
}

export interface SecurityStats {
  total_events: number;
  by_type: Record<string, number>;
  by_severity: Record<string, number>;
  unresolved_critical: number;
  period_days: number;
}

export interface IPWhitelist {
  id: number;
  ip_address: string;
  description?: string;
  is_active: boolean;
  created_at: string;
}

export interface IPBlacklist {
  id: number;
  ip_address: string;
  reason?: string;
  is_active: boolean;
  blocked_until?: string;
  created_at: string;
}

export interface OAuthProvider {
  id: number;
  name: string;
  display_name: string;
  is_active: boolean;
  is_sso_enabled: boolean;
  created_at: string;
}

export interface DataSubjectRequest {
  id: number;
  user_id?: number;
  email: string;
  request_type: string;
  status: string;
  description?: string;
  verified: boolean;
  verified_at?: string;
  assigned_to?: number;
  completed_at?: string;
  created_at: string;
}

class SecurityService {
  // Security Events
  async getSecurityEvents(params?: {
    user_id?: number;
    event_type?: string;
    severity?: string;
    ip_address?: string;
    resolved?: boolean;
    days?: number;
    limit?: number;
    offset?: number;
  }): Promise<SecurityEvent[]> {
    const response = await apiClient.get('/security/events', { params });
    return response.data;
  }

  async getSecurityStats(days: number = 7): Promise<SecurityStats> {
    const response = await apiClient.get('/security/events/stats', {
      params: { days }
    });
    return response.data;
  }

  async resolveSecurityEvent(eventId: number, resolutionNotes?: string): Promise<void> {
    await apiClient.post(`/security/events/${eventId}/resolve`, {
      resolution_notes: resolutionNotes
    });
  }

  // IP Whitelist
  async getWhitelistedIPs(): Promise<IPWhitelist[]> {
    const response = await apiClient.get('/security/ip/whitelist');
    return response.data;
  }

  async addIPToWhitelist(ipAddress: string, description?: string): Promise<void> {
    await apiClient.post('/security/ip/whitelist', {
      ip_address: ipAddress,
      description
    });
  }

  async removeIPFromWhitelist(ipAddress: string): Promise<void> {
    await apiClient.delete(`/security/ip/whitelist/${ipAddress}`);
  }

  // IP Blacklist
  async getBlacklistedIPs(): Promise<IPBlacklist[]> {
    const response = await apiClient.get('/security/ip/blacklist');
    return response.data;
  }

  async addIPToBlacklist(ipAddress: string, reason?: string, blockedUntil?: string): Promise<void> {
    await apiClient.post('/security/ip/blacklist', {
      ip_address: ipAddress,
      reason,
      blocked_until: blockedUntil
    });
  }

  async removeIPFromBlacklist(ipAddress: string): Promise<void> {
    await apiClient.delete(`/security/ip/blacklist/${ipAddress}`);
  }

  // OAuth Providers
  async getOAuthProviders(): Promise<OAuthProvider[]> {
    const response = await apiClient.get('/security/oauth/providers');
    return response.data;
  }

  async createOAuthProvider(data: {
    name: string;
    display_name: string;
    client_id: string;
    client_secret: string;
    authorization_url: string;
    token_url: string;
    userinfo_url: string;
    scopes?: string;
    is_active?: boolean;
    is_sso_enabled?: boolean;
  }): Promise<OAuthProvider> {
    const response = await apiClient.post('/security/oauth/providers', data);
    return response.data;
  }

  async updateOAuthProvider(providerId: number, data: Partial<{
    display_name: string;
    client_id: string;
    client_secret: string;
    authorization_url: string;
    token_url: string;
    userinfo_url: string;
    scopes: string;
    is_active: boolean;
    is_sso_enabled: boolean;
  }>): Promise<OAuthProvider> {
    const response = await apiClient.put(`/security/oauth/providers/${providerId}`, data);
    return response.data;
  }

  async deleteOAuthProvider(providerId: number): Promise<void> {
    await apiClient.delete(`/security/oauth/providers/${providerId}`);
  }

  async getOAuthAuthorizationUrl(providerName: string, redirectUri: string, state?: string): Promise<string> {
    const response = await apiClient.get(`/security/oauth/${providerName}/authorize`, {
      params: { redirect_uri: redirectUri, state }
    });
    return response.data.authorization_url;
  }

  // GDPR Requests
  async getGDPRRequests(params?: {
    status?: string;
    request_type?: string;
    limit?: number;
    offset?: number;
  }): Promise<DataSubjectRequest[]> {
    const response = await apiClient.get('/security/gdpr/requests', { params });
    return response.data;
  }

  async getGDPRRequest(requestId: number): Promise<DataSubjectRequest> {
    const response = await apiClient.get(`/security/gdpr/requests/${requestId}`);
    return response.data;
  }

  async assignGDPRRequest(requestId: number): Promise<void> {
    await apiClient.post(`/security/gdpr/requests/${requestId}/assign`);
  }

  async completeGDPRRequest(requestId: number, notes?: string): Promise<void> {
    await apiClient.post(`/security/gdpr/requests/${requestId}/complete`, { notes });
  }

  // GDPR
  async createDataSubjectRequest(email: string, requestType: string, description?: string): Promise<{ verification_token: string }> {
    const response = await apiClient.post('/security/gdpr/request', {
      email,
      request_type: requestType,
      description
    });
    return response.data;
  }

  async verifyDataSubjectRequest(verificationToken: string): Promise<void> {
    await apiClient.post(`/security/gdpr/verify/${verificationToken}`);
  }

  async getUserData(userId: number): Promise<Record<string, unknown>> {
    const response = await apiClient.get(`/security/gdpr/data/${userId}`);
    return response.data.data;
  }

  async exportUserData(userId: number): Promise<Record<string, unknown>> {
    const response = await apiClient.get(`/security/gdpr/export/${userId}`);
    return response.data.data;
  }

  async deleteUserData(userId: number): Promise<void> {
    await apiClient.delete(`/security/gdpr/data/${userId}`);
  }

  // Security Scanning
  async runSecurityScan(): Promise<Record<string, unknown>> {
    const response = await apiClient.post('/security/scan/run', {});
    return response.data.results;
  }

  async scheduleSecurityScan(intervalHours: number = 24): Promise<Record<string, unknown>> {
    const response = await apiClient.post('/security/scan/schedule', null, {
      params: { interval_hours: intervalHours }
    });
    return response.data.schedule;
  }
}

export const securityService = new SecurityService();
export default securityService;

