package com.arena.combat.entity;

import com.arena.combat.entity.enums.ClasePersonaje;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

@Entity
@Table(name = "usuarios", indexes = {
    @Index(name = "idx_usuarios_username", columnList = "username"),
    @Index(name = "idx_usuarios_email", columnList = "email")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Usuario {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true, length = 50)
    private String username;

    @Column(nullable = false, unique = true, length = 100)
    private String email;

    @Column(name = "password_hash", nullable = false)
    private String passwordHash;

    @Column(nullable = false)
    @Builder.Default
    private Integer nivel = 1;

    @Column(nullable = false)
    @Builder.Default
    private Integer experiencia = 0;

    @Column(name = "partidas_jugadas", nullable = false)
    @Builder.Default
    private Integer partidasJugadas = 0;

    @Column(name = "partidas_ganadas", nullable = false)
    @Builder.Default
    private Integer partidasGanadas = 0;

    @Enumerated(EnumType.STRING)
    @Column(name = "clase_personaje", nullable = false, length = 30)
    @Builder.Default
    private ClasePersonaje clasePersonaje = ClasePersonaje.GUERRERO;

    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(name = "updated_at", nullable = false)
    private LocalDateTime updatedAt;

    public void registrarVictoria(int expGanada) {
        this.partidasJugadas++;
        this.partidasGanadas++;
        this.experiencia += expGanada;
        verificarSubidaNivel();
    }

    public void registrarDerrota(int expConsuelo) {
        this.partidasJugadas++;
        this.experiencia += expConsuelo;
        verificarSubidaNivel();
    }

    private void verificarSubidaNivel() {
        int expRequerida = this.nivel * 100;
        while (this.experiencia >= expRequerida) {
            this.experiencia -= expRequerida;
            this.nivel++;
            expRequerida = this.nivel * 100;
        }
    }
}
