import { ERROR_CODES, type Result } from "$lib/core/data.types";
import { count, eq, type Database } from "@pkg/db";
import { order } from "@pkg/db/schema";
import { getError, Logger } from "@pkg/logger";
import { fullOrderModel, type FullOrderModel } from "./entities";

export class OrderRepository {
	private db: Database;

	constructor(db: Database) {
		this.db = db;
	}

	async getMyOrdersCount(requesterId: string): Promise<Result<number>> {
		const out = await this.db
			.select({ count: count() })
			.from(order)
			.where(eq(order.agentId, requesterId))
			.execute();
		return { data: out[0].count };
	}

	async listAllOrders(): Promise<Result<FullOrderModel[]>> {
		try {
			const res = await this.db.query.order.findMany({
				with: { customerInfo: true, product: true, paymentInfo: true },
			});
			const out = [] as FullOrderModel[];
			for (const each of res) {
				console.log(each);
				const parsed = fullOrderModel.safeParse({
					...each,
				});
				if (!parsed.success) {
					Logger.error(JSON.stringify(parsed.error.errors, null, 2));
					continue;
				}
				out.push(parsed.data);
			}
			return { data: out };
		} catch (e) {
			return {
				error: getError(
					{
						code: ERROR_CODES.INTERNAL_SERVER_ERROR,
						message: "An error occured while listing orders",
						userHint: "Please try again later",
						actionable: false,
						detail: "An error occured while listing orders",
					},
					e,
				),
			};
		}
	}

	async getOrder(oid: number): Promise<Result<FullOrderModel>> {
		const out = await this.db.query.order.findFirst({
			where: eq(order.id, oid),
			with: { customerInfo: true, product: true, paymentInfo: true },
		});
		console.log(out?.paymentInfo);
		if (!out) return {};
		const parsed = fullOrderModel.safeParse({
			...out,
		});
		if (!parsed.success) {
			return {
				error: getError(
					{
						code: ERROR_CODES.INTERNAL_SERVER_ERROR,
						message: "An error occured while parsing order",
						userHint: "Please try again later",
						actionable: false,
						detail: "An error occured while parsing order",
					},
					parsed.error,
				),
			};
		}
		return { data: parsed.data };
	}
}
