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

export interface YearEndClosing {
  id: number;
  company_id: number;
  fiscal_year_id: number;
  status: 'pending' | 'in_progress' | 'completed' | 'reopened';
  income_summary_account_id: number | null;
  retained_earnings_account_id: number | null;
  revenue_closing_entry_id: number | null;
  expense_closing_entry_id: number | null;
  income_summary_closing_entry_id: number | null;
  opening_balance_entry_id: number | null;
  total_revenue: number | null;
  total_expenses: number | null;
  net_income: number | null;
  executed_by: number | null;
  executed_at: string | null;
  reopened_by: number | null;
  reopened_at: string | null;
  notes: string | null;
  notes_ar: string | null;
  fiscal_year?: any;
  created_at: string;
  updated_at: string;
}

export interface ReadinessCheck {
  ready: boolean;
  issues: string[];
  summary: {
    total_revenue: string;
    total_expenses: string;
    net_income: string;
    revenue_accounts: any[];
    expense_accounts: any[];
  };
}

export interface ExecuteClosingRequest {
  income_summary_account_id: number;
  retained_earnings_account_id: number;
  notes?: string;
  notes_ar?: string;
}

@Injectable({ providedIn: 'root' })
export class YearEndClosingService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/accounting/year-end-closing`;

  list(page = 1, perPage = 100): Observable<{ data: YearEndClosing[] }> {
    const params = new HttpParams().set('page', page).set('per_page', perPage);
    return this.http.get<{ data: YearEndClosing[] }>(this.apiUrl, { params });
  }

  getByFiscalYear(fiscalYearId: number): Observable<{ data: YearEndClosing }> {
    return this.http.get<{ data: YearEndClosing }>(`${this.apiUrl}/${fiscalYearId}`);
  }

  checkReadiness(fiscalYearId: number): Observable<{ data: ReadinessCheck }> {
    return this.http.get<{ data: ReadinessCheck }>(`${this.apiUrl}/${fiscalYearId}/readiness`);
  }

  execute(fiscalYearId: number, data: ExecuteClosingRequest): Observable<{ data: YearEndClosing }> {
    return this.http.post<{ data: YearEndClosing }>(`${this.apiUrl}/${fiscalYearId}/execute`, data);
  }

  reopen(fiscalYearId: number): Observable<{ data: YearEndClosing }> {
    return this.http.post<{ data: YearEndClosing }>(`${this.apiUrl}/${fiscalYearId}/reopen`, {});
  }
}
