import { Injectable, inject } from '@angular/core';
import { Observable, map } from 'rxjs';
import { ApiService } from '../../../core/services/api.service';
import {
  DepartmentResponseDto,
  CreateDepartmentDto,
  UpdateDepartmentDto,
  PaginatedDepartmentsResponse,
  CreateDepartmentWithCredentialsResponse,
  RegenerateApiKeyResponse,
} from '../../../api/models';

interface ApiPaginatedResponse<T> {
  data: T[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

@Injectable({
  providedIn: 'root',
})
export class DepartmentService {
  private readonly api = inject(ApiService);

  getDepartments(page = 1, limit = 10): Observable<PaginatedDepartmentsResponse> {
    return this.api.get<ApiPaginatedResponse<DepartmentResponseDto>>('/departments', { page, limit }).pipe(
      map(response => {
        // Handle both wrapped {data, meta} and direct array responses
        const data = Array.isArray(response) ? response : (response?.data ?? []);
        const meta = Array.isArray(response) ? null : response?.meta;
        return {
          data,
          total: meta?.total ?? data.length,
          page: meta?.page ?? page,
          limit: meta?.limit ?? limit,
          totalPages: meta?.totalPages ?? Math.ceil(data.length / limit),
          hasNextPage: (meta?.page ?? 1) < (meta?.totalPages ?? 1),
        };
      })
    );
  }

  getDepartment(id: string): Observable<DepartmentResponseDto> {
    return this.api.get<DepartmentResponseDto>(`/departments/${id}`);
  }

  getDepartmentByCode(code: string): Observable<DepartmentResponseDto> {
    return this.api.get<DepartmentResponseDto>(`/departments/code/${code}`);
  }

  createDepartment(dto: CreateDepartmentDto): Observable<CreateDepartmentWithCredentialsResponse> {
    return this.api.post<CreateDepartmentWithCredentialsResponse>('/departments', dto);
  }

  updateDepartment(id: string, dto: UpdateDepartmentDto): Observable<DepartmentResponseDto> {
    return this.api.patch<DepartmentResponseDto>(`/departments/${id}`, dto);
  }

  deleteDepartment(id: string): Observable<void> {
    return this.api.delete<void>(`/departments/${id}`);
  }

  regenerateApiKey(id: string): Observable<RegenerateApiKeyResponse> {
    return this.api.post<RegenerateApiKeyResponse>(`/departments/${id}/regenerate-key`, {});
  }

  toggleActive(id: string, isActive: boolean): Observable<DepartmentResponseDto> {
    return this.api.patch<DepartmentResponseDto>(`/departments/${id}`, { isActive });
  }
}
