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

const Goal = @This();

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

pub fn tick(self: *Goal, goal_id: Artificer.GoalId, artificer: *Artificer) void {
    const store = artificer.server.store;
    const character = store.characters.get(artificer.character).?;

    if (self.quantity == 0) {
        artificer.removeGoal(goal_id);
        return;
    }

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

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

    if (!map_position.eql(character.position)) {
        artificer.queued_actions.appendAssumeCapacity(.{
            .goal = goal_id,
            .action = .{ .move = map_position }
        });
        return;
    }

    artificer.queued_actions.appendAssumeCapacity(.{
        .goal = goal_id,
        .action = .{ .gather = {} }
    });
}

pub fn requirements(self: Goal, artificer: *Artificer) Artificer.Requirements {
    _ = self;
    _ = artificer;

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

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

    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;
        }
    }
}

