// zig fmt: off
const Api = @import("artifacts-api");

const Artificer = @import("./artificer.zig");
const Context = Artificer.GoalContext;
const Requirements = Artificer.Requirements;

const Goal = @This();

item: Api.Store.Id,
quantity: u64,

pub fn tick(self: *Goal, ctx: *Context) void {
    if (self.quantity == 0) {
        ctx.completed = true;
        return;
    }

    const resource_id = ctx.findBestResourceWithItem(self.item) orelse @panic("Failed to find resource with item");

    const map_position: Api.Position = ctx.findNearestMapWithResource(resource_id) orelse @panic("Map with resource not found");

    if (!map_position.eql(ctx.character.position)) {
        ctx.queueAction(.{
            .move = map_position
        });
        return;
    }

    // TODO: Check for enough space in invetory? Or add it as a requirement
    ctx.queueAction(.{
        .gather = {}
    });
}

pub fn requirements(self: Goal, ctx: *Context) Requirements {
    _ = ctx;
    _ = self;

    const reqs: Requirements = .{};
    // TODO: add skill requirement
    return reqs;
}

pub fn onActionCompleted(self: *Goal, ctx: *Context, result: Artificer.ActionResult) void {
    _ = ctx;

    if (result == .gather) {
        const gather_result = result.gather;
        const gather_quantity = gather_result.details.items.getQuantity(self.item);

        if (self.quantity > gather_quantity) {
            self.quantity -= gather_quantity;
        } else {
            self.quantity = 0;
        }
    }
}

