package classes

import (
	"dk/internal/database"
	"fmt"
	"strings"
)

type Class struct {
	ID      int
	Name    string
	Lore    string
	BaseHP  int
	BaseMP  int
	BaseSTR int
	BaseDEX int
	RateHP  int
	RateMP  int
	RateSTR int
	RateDEX int
}

func New() *Class {
	return &Class{
		BaseHP:  15,
		BaseMP:  10,
		BaseSTR: 1,
		BaseDEX: 1,
		RateHP:  2,
		RateMP:  2,
		RateSTR: 2,
		RateDEX: 2,
	}
}

func (c *Class) Validate() error {
	if strings.TrimSpace(c.Name) == "" {
		return fmt.Errorf("class name cannot be empty")
	}
	if c.BaseHP < 1 {
		return fmt.Errorf("class base HP must be at least 1")
	}
	if c.BaseMP < 0 {
		return fmt.Errorf("class base MP must be at least 0")
	}
	if c.BaseSTR < 0 {
		return fmt.Errorf("class base strength must be at least 0")
	}
	if c.BaseDEX < 0 {
		return fmt.Errorf("class base dexterity must be at least 0")
	}
	if c.RateHP < 0 {
		return fmt.Errorf("class HP rate must be at least 0")
	}
	if c.RateMP < 0 {
		return fmt.Errorf("class MP rate must be at least 0")
	}
	if c.RateSTR < 0 {
		return fmt.Errorf("class strength rate must be at least 0")
	}
	if c.RateDEX < 0 {
		return fmt.Errorf("class dexterity rate must be at least 0")
	}
	return nil
}

func (c *Class) Delete() error {
	return database.Exec("DELETE FROM classes WHERE id = %d", c.ID)
}

func (c *Class) Insert() error {
	id, err := database.Insert("classes", c, "id")
	if err != nil {
		return err
	}
	c.ID = int(id)
	return nil
}

func Find(id int) (*Class, error) {
	var class Class
	err := database.Get(&class, "SELECT * FROM classes WHERE id = %d", id)
	if err != nil {
		return nil, fmt.Errorf("class with ID %d not found", id)
	}
	return &class, nil
}

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