import * as v from "valibot";

export enum TaskStatus {
    PENDING = "pending",
    RUNNING = "running",
    COMPLETED = "completed",
    FAILED = "failed",
    CANCELLED = "cancelled",
}

export const taskStatusSchema = v.picklist([
    "pending",
    "running",
    "completed",
    "failed",
    "cancelled",
]);
export type TaskStatusType = v.InferOutput<typeof taskStatusSchema>;

export enum TaskType {
    APK_BUILD = "apk_build",
}

export const taskTypeSchema = v.picklist(["apk_build"]);
export type TaskTypeValue = v.InferOutput<typeof taskTypeSchema>;

export const taskErrorSchema = v.object({
    code: v.string(),
    message: v.string(),
    detail: v.optional(v.string()),
    timestamp: v.date(),
});
export type TaskError = v.InferOutput<typeof taskErrorSchema>;

export const taskSchema = v.object({
    id: v.string(),
    type: taskTypeSchema,
    status: taskStatusSchema,
    progress: v.pipe(v.number(), v.integer()),
    payload: v.optional(v.nullable(v.record(v.string(), v.any()))),
    result: v.optional(v.nullable(v.record(v.string(), v.any()))),
    error: v.optional(v.nullable(taskErrorSchema)),
    userId: v.string(),
    resourceId: v.string(),
    startedAt: v.optional(v.nullable(v.date())),
    completedAt: v.optional(v.nullable(v.date())),
    createdAt: v.date(),
    updatedAt: v.date(),
});
export type Task = v.InferOutput<typeof taskSchema>;

export const createTaskSchema = v.object({
    id: v.string(),
    type: taskTypeSchema,
    status: v.optional(taskStatusSchema),
    progress: v.optional(v.pipe(v.number(), v.integer())),
    payload: v.optional(v.nullable(v.record(v.string(), v.any()))),
    userId: v.string(),
    resourceId: v.string(),
});
export type CreateTask = v.InferOutput<typeof createTaskSchema>;

export const updateTaskSchema = v.object({
    status: v.optional(taskStatusSchema),
    progress: v.optional(v.pipe(v.number(), v.integer())),
    result: v.optional(v.nullable(v.record(v.string(), v.any()))),
    error: v.optional(v.nullable(taskErrorSchema)),
    startedAt: v.optional(v.nullable(v.date())),
    completedAt: v.optional(v.nullable(v.date())),
});
export type UpdateTask = v.InferOutput<typeof updateTaskSchema>;
