package items

import (
	"fmt"

	"dk/internal/database"
)

// Item represents an item in the game
type Item struct {
	ID      int
	Type    int
	Name    string
	Value   int
	Att     int
	Special string
}

// ItemType constants for item types
const (
	TypeWeapon = 1
	TypeArmor  = 2
	TypeShield = 3
)

// New creates a new Item with sensible defaults
func New() *Item {
	return &Item{
		Type:    TypeWeapon,
		Name:    "",
		Value:   0,
		Att:     0,
		Special: "",
	}
}

// Validate checks if item has valid values
func (i *Item) Validate() error {
	if i.Name == "" {
		return fmt.Errorf("item name cannot be empty")
	}
	if i.Type < TypeWeapon || i.Type > TypeShield {
		return fmt.Errorf("invalid item type: %d", i.Type)
	}
	if i.Value < 0 {
		return fmt.Errorf("item Value cannot be negative")
	}
	if i.Att < 0 {
		return fmt.Errorf("item Att cannot be negative")
	}
	return nil
}

// CRUD operations
func (i *Item) Delete() error {
	return database.Exec("DELETE FROM items WHERE id = %d", i.ID)
}

func (i *Item) Insert() error {
	id, err := database.Insert("items", i, "ID")
	if err != nil {
		return err
	}
	i.ID = int(id)
	return nil
}

// Query functions
func Find(id int) (*Item, error) {
	var item Item
	err := database.Get(&item, "SELECT * FROM items WHERE id = %d", id)
	if err != nil {
		return nil, fmt.Errorf("item with ID %d not found", id)
	}
	return &item, nil
}

func All() ([]*Item, error) {
	var items []*Item
	err := database.Select(&items, "SELECT * FROM items ORDER BY id ASC")
	return items, err
}

func ByType(itemType int) ([]*Item, error) {
	var items []*Item
	err := database.Select(&items, "SELECT * FROM items WHERE type = %d ORDER BY id ASC", itemType)
	return items, err
}

// Helper methods
func (i *Item) IsWeapon() bool {
	return i.Type == TypeWeapon
}

func (i *Item) IsArmor() bool {
	return i.Type == TypeArmor
}

func (i *Item) IsShield() bool {
	return i.Type == TypeShield
}

func (i *Item) TypeName() string {
	switch i.Type {
	case TypeWeapon:
		return "Weapon"
	case TypeArmor:
		return "Armor"
	case TypeShield:
		return "Shield"
	default:
		return "Unknown"
	}
}

func (i *Item) HasSpecial() bool {
	return i.Special != ""
}

func (i *Item) IsEquippable() bool {
	return i.Type == TypeWeapon || i.Type == TypeArmor || i.Type == TypeShield
}
