import type {
  RfidCardBatch,
  RfidCardBatchDetail,
  RfidCardBatchStats,
} from "@/domain/entities/rfid-card-batch";
import type { RfidCardBatchRepository } from "@/domain/repositories/rfid-card-batch.repository";
import type { BackendPaginatedData, PaginationQueryParams } from "@/shared/types";
import { api } from "@/infrastructure/api/api-client";

/**
 * The list endpoint returns a camelCase envelope keyed by `batches` instead of
 * the app-standard snake_case `items` shape, so we normalise it to
 * BackendPaginatedData here — the presentation layer stays consistent with the
 * other modules.
 */
interface RfidBatchListRaw {
  total: number;
  count: number;
  per_page: number;
  currentPage: number;
  lastPage: number;
  totalPages: number;
  previousPageUrl: string | null;
  nextPageUrl: string | null;
  batches: RfidCardBatch[];
}

export class RfidCardBatchRepositoryImpl implements RfidCardBatchRepository {
  getStats() {
    return api.get<RfidCardBatchStats>("/rfid-card-batches/stats");
  }

  async findAll(
    params: PaginationQueryParams,
  ): Promise<BackendPaginatedData<RfidCardBatch>> {
    const raw = await api.get<RfidBatchListRaw>("/rfid-card-batches", { params });
    return {
      total: raw.total,
      count: raw.count,
      per_page: raw.per_page,
      current_page: raw.currentPage,
      last_page: raw.lastPage,
      previous_page_url: raw.previousPageUrl,
      next_page_url: raw.nextPageUrl,
      items: raw.batches ?? [],
    };
  }

  findById(id: number) {
    return api.get<RfidCardBatchDetail>(`/rfid-card-batches/${id}`);
  }

  process(id: number) {
    return api.post<RfidCardBatchDetail>(`/rfid-card-batches/${id}/process`);
  }
}
