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

export interface Country {
  code: string;
  name: string;
  name_ar: string;
}

const FALLBACK_COUNTRIES: Country[] = [
  { code: 'KW', name: 'Kuwait', name_ar: 'الكويت' },
  { code: 'SA', name: 'Saudi Arabia', name_ar: 'السعودية' },
  { code: 'AE', name: 'United Arab Emirates', name_ar: 'الإمارات' },
  { code: 'EG', name: 'Egypt', name_ar: 'مصر' },
  { code: 'BH', name: 'Bahrain', name_ar: 'البحرين' },
  { code: 'QA', name: 'Qatar', name_ar: 'قطر' },
  { code: 'OM', name: 'Oman', name_ar: 'عُمان' },
  { code: 'JO', name: 'Jordan', name_ar: 'الأردن' },
  { code: 'LB', name: 'Lebanon', name_ar: 'لبنان' },
  { code: 'IQ', name: 'Iraq', name_ar: 'العراق' },
  { code: 'SY', name: 'Syria', name_ar: 'سوريا' },
  { code: 'PS', name: 'Palestine', name_ar: 'فلسطين' },
  { code: 'YE', name: 'Yemen', name_ar: 'اليمن' },
  { code: 'LY', name: 'Libya', name_ar: 'ليبيا' },
  { code: 'TN', name: 'Tunisia', name_ar: 'تونس' },
  { code: 'DZ', name: 'Algeria', name_ar: 'الجزائر' },
  { code: 'MA', name: 'Morocco', name_ar: 'المغرب' },
  { code: 'SD', name: 'Sudan', name_ar: 'السودان' },
  { code: 'TR', name: 'Turkey', name_ar: 'تركيا' },
  { code: 'US', name: 'United States', name_ar: 'الولايات المتحدة' },
  { code: 'GB', name: 'United Kingdom', name_ar: 'المملكة المتحدة' },
  { code: 'DE', name: 'Germany', name_ar: 'ألمانيا' },
  { code: 'FR', name: 'France', name_ar: 'فرنسا' },
  { code: 'IN', name: 'India', name_ar: 'الهند' },
  { code: 'PK', name: 'Pakistan', name_ar: 'باكستان' },
  { code: 'CN', name: 'China', name_ar: 'الصين' },
];

@Injectable({ providedIn: 'root' })
export class CountryService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/core/countries`;

  getById(id: string | number): Observable<{ data: any }> {
    return this.http.get<{ data: any }>(`${this.apiUrl}/${id}`);
  }

  getCountries(): Observable<Country[]> {
    return this.http.get<{ data: any[] }>(this.apiUrl).pipe(
      map(response => {
        if (response.data && response.data.length > 0) {
          return response.data.map(c => ({
            code: c.code || c.id,
            name: c.name_en || c.name,
            name_ar: c.name_ar || c.name,
          }));
        }
        return FALLBACK_COUNTRIES;
      }),
      catchError(() => of(FALLBACK_COUNTRIES))
    );
  }
}
