import axios, { AxiosError, AxiosInstance } from 'axios';
import { useAuthStore } from '@/store/auth-store';

class ApiClient {
  private client: AxiosInstance;

  constructor() {
    this.client = axios.create({
      baseURL: '/api',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // Request interceptor to add auth token
    this.client.interceptors.request.use(
      (config) => {
        const token = useAuthStore.getState().token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // Response interceptor to handle errors
    this.client.interceptors.response.use(
      (response) => response,
      async (error: AxiosError) => {
        if (error.response?.status === 401) {
          // Token expired or invalid
          useAuthStore.getState().logout();
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }

  // Auth endpoints
  async login(email: string, password: string) {
    const response = await this.client.post('/auth/login', { email, password });
    return response.data;
  }

  async register(data: { email: string; password: string; name?: string; company?: string }) {
    const response = await this.client.post('/auth/register', data);
    return response.data;
  }

  async getMe() {
    const response = await this.client.get('/auth/me');
    return response.data;
  }

  async refreshApiKey() {
    const response = await this.client.post('/auth/refresh-api-key');
    return response.data;
  }

  // Website endpoints
  async getWebsites(params?: { page?: number; limit?: number; search?: string }) {
    const response = await this.client.get('/websites', { params });
    return response.data;
  }

  async getWebsite(id: string) {
    const response = await this.client.get(`/websites/${id}`);
    return response.data;
  }

  async createWebsite(data: any) {
    const response = await this.client.post('/websites', data);
    return response.data;
  }

  async updateWebsite(id: string, data: any) {
    const response = await this.client.patch(`/websites/${id}`, data);
    return response.data;
  }

  async deleteWebsite(id: string) {
    const response = await this.client.delete(`/websites/${id}`);
    return response.data;
  }

  async getWebsiteScans(id: string, params?: { page?: number; limit?: number }) {
    const response = await this.client.get(`/websites/${id}/scans`, { params });
    return response.data;
  }

  // Scan endpoints
  async createScan(data: { websiteId: string; url?: string; options?: any }) {
    const response = await this.client.post('/scans', data);
    return response.data;
  }

  async getScan(id: string) {
    const response = await this.client.get(`/scans/${id}`);
    return response.data;
  }

  async getScanResult(id: string) {
    const response = await this.client.get(`/scans/${id}/result`);
    return response.data;
  }

  async getScanViolations(id: string, params?: { impact?: string; tag?: string }) {
    const response = await this.client.get(`/scans/${id}/violations`, { params });
    return response.data;
  }

  async cancelScan(id: string) {
    const response = await this.client.delete(`/scans/${id}`);
    return response.data;
  }

  async getScans(params?: { page?: number; limit?: number; status?: string; websiteId?: string }) {
    const response = await this.client.get('/scans', { params });
    return response.data;
  }

  // Report endpoints
  async generateReport(data: {
    websiteId: string;
    type: 'COMPLIANCE' | 'EXECUTIVE' | 'TECHNICAL' | 'TREND';
    format: 'PDF' | 'HTML' | 'JSON' | 'CSV';
    period: { start: string; end: string };
  }) {
    const response = await this.client.post('/reports/generate', data);
    return response.data;
  }

  async getReports(params?: { page?: number; limit?: number; websiteId?: string; type?: string }) {
    const response = await this.client.get('/reports', { params });
    return response.data;
  }

  async getReport(id: string) {
    const response = await this.client.get(`/reports/${id}`);
    return response.data;
  }

  async downloadReport(id: string) {
    const response = await this.client.get(`/reports/${id}/download`);
    return response.data;
  }

  async getComplianceTrends(websiteId: string, days: number = 30) {
    const response = await this.client.get(`/reports/trends/${websiteId}`, { params: { days } });
    return response.data;
  }

  // Health endpoints
  async getHealth() {
    const response = await this.client.get('/health');
    return response.data;
  }

  async getStats() {
    const response = await this.client.get('/health/stats');
    return response.data;
  }
}

export const apiClient = new ApiClient();