import { db } from "@pkg/db";
import { FlowExecCtx } from "@core/flow.execution.context";
import { CreateTask, TaskStatus, TaskType, UpdateTask } from "./data";
import { TasksRepository } from "./repository";

export class TasksController {
    constructor(private tasksRepo: TasksRepository) {}

    createTask(fctx: FlowExecCtx, taskData: CreateTask) {
        return this.tasksRepo.createTask(fctx, taskData);
    }

    getTaskById(fctx: FlowExecCtx, taskId: string) {
        return this.tasksRepo.getTaskById(fctx, taskId);
    }

    updateTask(fctx: FlowExecCtx, taskId: string, updates: UpdateTask) {
        return this.tasksRepo.updateTask(fctx, taskId, updates);
    }

    deleteTask(fctx: FlowExecCtx, taskId: string) {
        return this.tasksRepo.deleteTask(fctx, taskId);
    }

    getTasksByStatuses(fctx: FlowExecCtx, statuses: TaskStatus[]) {
        return this.tasksRepo.getTasksByStatuses(fctx, statuses);
    }

    getTasksByTypeAndStatuses(
        fctx: FlowExecCtx,
        type: TaskType,
        statuses: TaskStatus[],
    ) {
        return this.tasksRepo.getTasksByTypeAndStatuses(fctx, type, statuses);
    }

    markTaskAsCompleted(
        fctx: FlowExecCtx,
        taskId: string,
        result?: Record<string, any>,
    ) {
        return this.tasksRepo.markTaskAsCompleted(fctx, taskId, result);
    }

    markTaskAsFailed(fctx: FlowExecCtx, taskId: string, error: any) {
        return this.tasksRepo.markTaskAsFailed(fctx, taskId, error);
    }

    updateTaskProgress(fctx: FlowExecCtx, taskId: string, progress: number) {
        return this.tasksRepo.updateTask(fctx, taskId, {
            progress: Math.max(0, Math.min(100, progress)),
        });
    }

    cancelTask(fctx: FlowExecCtx, taskId: string) {
        return this.tasksRepo.updateTask(fctx, taskId, {
            status: TaskStatus.CANCELLED,
            completedAt: new Date(),
        });
    }

    startTask(fctx: FlowExecCtx, taskId: string) {
        return this.tasksRepo.updateTask(fctx, taskId, {
            status: TaskStatus.RUNNING,
            startedAt: new Date(),
        });
    }
}

export function getTasksController(): TasksController {
    return new TasksController(new TasksRepository(db));
}
