using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Aeldria.Api.Data;
using Aeldria.Api.Models;
using Aeldria.Api.DTOs;

namespace Aeldria.Api.Controllers;

[ApiController]
[Authorize]
[Route("api/[controller]")]
public class CharactersController : ControllerBase
{
    private readonly AeldriaDbContext _db;

    public CharactersController(AeldriaDbContext db)
    {
        _db = db;
    }

    [HttpPost("create")]
    public async Task<IActionResult> Create(CreateCharacterRequest request)
    {
        if (await _db.Characters.AnyAsync(x => x.Name == request.Name))
            return BadRequest("Nom déjà utilisé.");
	var accountId = long.Parse(
		User.FindFirst(
			System.Security.Claims.ClaimTypes.NameIdentifier
		)!.Value
	);
        var character = new Character
        {
            AccountId = accountId,
            Name = request.Name,
            Level = 1,
            Experience = 0,
            PosX = 0,
            PosY = 0,
            PosZ = 0,
            CreatedAt = DateTime.UtcNow,
            FactionId = 1,
            RaceId = 1
        };

        _db.Characters.Add(character);
        await _db.SaveChangesAsync();

        return Ok(character);
    }

    [HttpGet("my")]
    public async Task<IActionResult> GetCharacters()
    {
	 var accountId = long.Parse(
         	User.FindFirst(
            		System.Security.Claims.ClaimTypes.NameIdentifier
        	)!.Value
    	);
        var characters = await _db.Characters
            .Where(x => x.AccountId == accountId)
            .ToListAsync();

        return Ok(characters);
    }
    [HttpGet("{characterId}")]
    public async Task<IActionResult> GetCharacter(long characterId)
    {
         var character = await _db.Characters
           .FirstOrDefaultAsync(x => x.CharacterId == characterId);

         if (character == null)
             return NotFound();

          return Ok(character);
    }
    [HttpPut("position")]
    public async Task<IActionResult> UpdatePosition(UpdatePositionRequest request)
    {
         var character = await _db.Characters
            .FirstOrDefaultAsync(x => x.CharacterId == request.CharacterId);

         if (character == null)
            return NotFound();

          character.PosX = request.PosX;
          character.PosY = request.PosY;
          character.PosZ = request.PosZ;

          await _db.SaveChangesAsync();

          return Ok(new
          {
            Message = "Position sauvegardée."
          });
    }

}
