import type { OrderRepository } from "../data/repository";
import type { UserModel } from "@pkg/logic/domains/user/data/entities";
import type { PaginationModel } from "@pkg/logic/core/pagination.utils";
import { ERROR_CODES, type Result } from "@pkg/result";
import { getError } from "@pkg/logger";
import type { PaginatedOrderInfoModel } from "../data/entities";

export class OrderController {
	private repo: OrderRepository;

	constructor(repo: OrderRepository) {
		this.repo = repo;
	}

	async listAllOrders() {
		return this.repo.listAllOrders();
	}

	async getOrder(oid: number) {
		return this.repo.getOrder(oid);
	}

	// Add this new method
	async getOrdersPaginatedInfo(
		user: UserModel,
		pInfo: PaginationModel,
		fetchNext: boolean,
	): Promise<Result<PaginatedOrderInfoModel>> {
		try {
			const orders = await this.repo.listAllOrders();
			if (orders.error) {
				return { error: orders.error };
			}

			// Calculate pagination
			const totalItems = orders.data?.length || 0;
			const totalPages = Math.max(1, Math.ceil(totalItems / pInfo.limit));
			const currentPage = Math.min(pInfo.page || 1, totalPages);

			// Extract the page of data
			const startIndex = (currentPage - 1) * pInfo.limit;
			const endIndex = Math.min(startIndex + pInfo.limit, totalItems);
			const pageData = orders.data?.slice(startIndex, endIndex) || [];

			return {
				data: {
					data: pageData,
					cursor: pInfo.cursor,
					limit: pInfo.limit,
					asc: pInfo.asc,
					totalItemCount: totalItems,
					totalPages: totalPages,
					page: currentPage,
				},
			};
		} catch (err) {
			return {
				error: getError(
					{
						code: ERROR_CODES.INTERNAL_SERVER_ERROR,
						message: "Failed to fetch orders",
						userHint: "Please try again later",
						actionable: false,
						detail: "Error occurred while fetching orders",
					},
					err,
				),
			};
		}
	}
}
