import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';

export interface AiSettings {
  id: number;
  company_id: number;
  default_provider: 'deepseek' | 'openai';
  deepseek_api_key: string | null;
  deepseek_model: string;
  openai_api_key: string | null;
  openai_model: string;
  max_tokens_per_request: number;
  monthly_token_limit: number | null;
  usd_to_egp_rate: string;
  cache_enabled: boolean;
  cache_ttl_hours: number;
  is_enabled: boolean;
  created_at: string;
  updated_at: string;
}

export interface AiPreferences {
  id: number;
  user_id: number;
  preferred_provider: 'auto' | 'deepseek' | 'openai';
  is_enabled: boolean;
  created_at: string;
  updated_at: string;
}

export interface AiUsage {
  totals: {
    total_requests: number;
    total_tokens: number;
    total_cost_usd: number;
    total_cost_egp: number;
    cached_requests: number;
  };
  by_provider: {
    provider: string;
    total_requests: number;
    total_tokens: number;
    total_cost_usd: number;
  }[];
  by_user: {
    user_id: number;
    user_name: string;
    total_requests: number;
    total_tokens: number;
    total_cost_usd: number;
  }[];
}

export interface AiMyUsage {
  totals: {
    total_requests: number;
    total_tokens: number;
    total_cost_usd: number;
    total_cost_egp: number;
    cached_requests: number;
  };
  recent: {
    id: number;
    provider: string;
    tokens_used: number;
    cost_usd: number;
    cached: boolean;
    created_at: string;
  }[];
}

@Injectable({ providedIn: 'root' })
export class AiSettingsService {
  private apiUrl = `${environment.apiUrl}/ai`;

  constructor(private http: HttpClient) {}

  getSettings(): Observable<AiSettings> {
    return this.http.get<any>(`${this.apiUrl}/settings`).pipe(map((res) => res.data));
  }

  updateSettings(data: Partial<AiSettings>): Observable<AiSettings> {
    return this.http.put<any>(`${this.apiUrl}/settings`, data).pipe(map((res) => res.data));
  }

  getPreferences(): Observable<AiPreferences> {
    return this.http.get<any>(`${this.apiUrl}/preferences`).pipe(map((res) => res.data));
  }

  updatePreferences(data: Partial<AiPreferences>): Observable<AiPreferences> {
    return this.http.put<any>(`${this.apiUrl}/preferences`, data).pipe(map((res) => res.data));
  }

  getUsage(params?: { provider?: string; from?: string; to?: string }): Observable<AiUsage> {
    return this.http
      .get<any>(`${this.apiUrl}/usage`, { params: params as any })
      .pipe(map((res) => res.data));
  }

  getMyUsage(params?: { from?: string; to?: string }): Observable<AiMyUsage> {
    return this.http
      .get<any>(`${this.apiUrl}/my-usage`, { params: params as any })
      .pipe(map((res) => res.data));
  }
}
