package actions import ( "dk/internal/database" "dk/internal/helpers" "dk/internal/models/items" "dk/internal/models/towns" "dk/internal/models/users" "fmt" "maps" ) // RestAtInn handles the inn resting logic func RestAtInn(user *users.User, town *towns.Town) error { if user.Gold < town.InnCost { return fmt.Errorf("you can't afford to stay here tonight") } return database.Transaction(func() error { return database.Update("users", map[string]any{ "gold": user.Gold - town.InnCost, "hp": user.MaxHP, "mp": user.MaxMP, "tp": user.MaxTP, }, "id", user.ID) }) } // BuyShopItem handles purchasing an item from a town shop func BuyShopItem(user *users.User, town *towns.Town, itemID int) error { // Validate item exists in shop if !town.HasShopItem(itemID) { return fmt.Errorf("the item doesn't exist in this shop") } // Get item details item, err := items.Find(itemID) if err != nil { return fmt.Errorf("error purchasing item: %v", err) } // Check user has enough gold if user.Gold < item.Value { return fmt.Errorf("you don't have enough gold to buy %s", item.Name) } // Get equipment updates from existing actions equipUpdates, err := UserEquipItem(user, item) if err != nil { return fmt.Errorf("cannot equip item: %v", err) } // Execute purchase transaction return database.Transaction(func() error { // Start with gold deduction updates := map[string]any{ "gold": user.Gold - item.Value, } // Add equipment updates maps.Copy(updates, equipUpdates) return database.Update("users", updates, "id", user.ID) }) } // BuyTownMap handles purchasing a town map func BuyTownMap(user *users.User, townID int) error { // Get the town being mapped mappedTown, err := towns.Find(townID) if err != nil { return fmt.Errorf("error purchasing map: %v", err) } // Check user has enough gold if user.Gold < mappedTown.MapCost { return fmt.Errorf("you don't have enough gold to buy the map to %s", mappedTown.Name) } // Get current town IDs and add new one townIDs := user.GetTownIDs() townIDs = append(townIDs, townID) newTownsString := helpers.IntsToString(townIDs) // Execute purchase transaction return database.Transaction(func() error { return database.Update("users", map[string]any{ "gold": user.Gold - mappedTown.MapCost, "towns": newTownsString, }, "id", user.ID) }) }