import { db } from "@pkg/db";
import type { FlowInfo, PendingAction } from "./data";
import { CheckoutFlowRepository } from "./repository";
import { getError } from "@pkg/logger";
import { ERROR_CODES } from "@pkg/result";

export class CheckoutFlowUseCases {
	constructor(private repo: CheckoutFlowRepository) {}

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

	async getAllSessionsList(includeDeleted: boolean = false) {
		return this.repo.getAllSessionsList(includeDeleted);
	}

	async getFlowInfo(flowId: string) {
		const out = await this.repo.getFlowInfo(flowId);
		return out;
	}

	async updateFlowState(id: string, state: FlowInfo) {
		return this.repo.updateFlowState(id, state);
	}

	async cleanupFlow(id: string) {
		return this.repo.cleanupFlow(id);
	}

	async softDeleteFlow(id: string) {
		return this.repo.softDeleteFlow(id);
	}

	async restoreFlow(id: string) {
		return this.repo.restoreFlow(id);
	}

	async addPendingAction(flowId: string, action: PendingAction) {
		try {
			// Add new action to pending actions
			return this.repo.addPendingAction(flowId, action);
		} catch (error) {
			return {
				error: getError(
					{
						code: ERROR_CODES.API_ERROR,
						message: "Failed to add pending action",
						userHint: "Please try again.",
						detail: "Error occurred when adding pending action to flow",
					},
					error,
				),
			};
		}
	}
}

export function getCKUseCases() {
	const repo = new CheckoutFlowRepository(db);
	return new CheckoutFlowUseCases(repo);
}
