import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { bilingual } from '../../../shared/i18n/bilingual';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
  ExpenseCategoryGroupDto, CreateExpenseGroupRequest, UpdateExpenseGroupRequest,
  CreateExpenseSubCategoryRequest, UpdateExpenseSubCategoryRequest,
  ExpenseCategoryAiRequest, CategoryAiSuggestion,
} from '../models/expense.model';
import { Form990ExpenseLineDto } from '../../finance-report/models/form990-report.model';
import { Form1099Box } from '../../payee1099/models/payee1099.model';

@Injectable({ providedIn: 'root' })
export class ExpenseCategoryApiService {
  private readonly endpoint: string;
  constructor(private http: HttpClient, private apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('expense-categories');
  }
  getAll(includeInactive = false): Observable<ExpenseCategoryGroupDto[]> {
    return this.http.get<ExpenseCategoryGroupDto[]>(this.endpoint, { params: new HttpParams().set('includeInactive', includeInactive) }).pipe(
      map(groups => groups.map(g => ({
        ...g,
        label: bilingual(g.name_en, g.name_zh),
        subCategories: g.subCategories.map(s => ({ ...s, label: bilingual(s.name_en, s.name_zh) })),
      }))),
    );
  }
  createGroup(r: CreateExpenseGroupRequest): Observable<{ id: number }> { return this.http.post<{ id: number }>(`${this.endpoint}/groups`, r); }
  updateGroup(id: number, r: UpdateExpenseGroupRequest): Observable<void> { return this.http.put<void>(`${this.endpoint}/groups/${id}`, r); }
  deactivateGroup(id: number): Observable<void> { return this.http.delete<void>(`${this.endpoint}/groups/${id}`); }
  createSub(r: CreateExpenseSubCategoryRequest): Observable<{ id: number }> { return this.http.post<{ id: number }>(`${this.endpoint}/subcategories`, r); }
  updateSub(id: number, r: UpdateExpenseSubCategoryRequest): Observable<void> { return this.http.put<void>(`${this.endpoint}/subcategories/${id}`, r); }
  deactivateSub(id: number): Observable<void> { return this.http.delete<void>(`${this.endpoint}/subcategories/${id}`); }
  aiSuggest(req: ExpenseCategoryAiRequest): Observable<CategoryAiSuggestion> {
    return this.http.post<CategoryAiSuggestion>(`${this.endpoint}/ai-suggest`, req);
  }
  getForm990Lines(): Observable<Form990ExpenseLineDto[]> {
    return this.http.get<Form990ExpenseLineDto[]>(this.apiConfig.getApiUrl('form990-report') + '/lines')
      .pipe(map(rows => rows.map(r => ({ ...r, label: `${r.lineCode} — ${r.name_en}${r.name_zh ? ' / ' + r.name_zh : ''}` }))));
  }

  getForm1099Boxes(): Observable<(Form1099Box & { label: string })[]> {
    return this.http.get<Form1099Box[]>(this.apiConfig.getApiUrl('form1099-report') + '/boxes')
      .pipe(map(rows => rows.map(b => ({ ...b, label: `${b.boxCode} — ${b.name_en}${b.name_zh ? ' / ' + b.name_zh : ''}` }))));
  }
}
