import { env } from './env';

const API_BASE_URL = typeof window !== 'undefined' 
  ? window.location.origin 
  : env.NEXTAUTH_URL;

export interface ApiResponse<T = unknown> {
  data?: T;
  error?: string;
  message?: string;
}

export class ApiClient {
  private baseURL: string;

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL;
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseURL}${endpoint}`;
    
    const defaultHeaders = {
      'Content-Type': 'application/json',
    };

    const config: RequestInit = {
      ...options,
      headers: {
        ...defaultHeaders,
        ...options.headers,
      },
    };

    try {
      const response = await fetch(url, config);
      const data = await response.json();

      if (!response.ok) {
        return {
          error: data.error || 'A apărut o eroare',
        };
      }

      return { data };
    } catch (error) {
      console.error('API request failed:', error);
      return {
        error: 'A apărut o eroare de rețea',
      };
    }
  }

  async post<T>(endpoint: string, data: unknown): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async get<T>(endpoint: string, token?: string): Promise<ApiResponse<T>> {
    const headers: Record<string, string> = {};
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    return this.request<T>(endpoint, {
      method: 'GET',
      headers,
    });
  }

  // Auth methods
  async login(email: string, password: string) {
    return this.post('/api/auth/login', { email, password });
  }

  async register(name: string, email: string, password: string) {
    return this.post('/api/auth/register', { name, email, password });
  }

  async forgotPassword(email: string) {
    return this.post('/api/auth/forgot-password', { email });
  }

  async resetPassword(token: string, password: string) {
    return this.post('/api/auth/reset-password', { token, password });
  }

  async verifyToken(token: string) {
    return this.post('/api/auth/verify', { token });
  }

  // Reports methods
  async getReports(token: string) {
    return this.get('/api/reports', token);
  }

  async getReport(id: string, token: string) {
    return this.get(`/api/reports/${id}`, token);
  }

  async createReport(data: {
    name: string;
    title: string;
    data: Record<string, unknown>;
    results?: Record<string, unknown>;
  }, token: string) {
    return this.request<{
      report: {
        id: string;
        name: string;
        title: string;
        createdAt: string;
        updatedAt: string;
      };
    }>('/api/reports', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  }

  async deleteReport(id: string, token: string) {
    return this.request(`/api/reports/${id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  }

  // Profile methods
  async updateProfile(data: {
    name: string;
    email: string;
  }, token: string) {
    return this.request('/api/profile', {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  }

  async updatePassword(data: {
    currentPassword: string;
    newPassword: string;
  }, token: string) {
    return this.request('/api/profile/password', {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  }
}

export const apiClient = new ApiClient();
