
using Microsoft.AspNetCore.Mvc.RazorPages;
using NetinaShop.Core.EntityServices.Abstracts;
using NetinaShop.Repository.Abstracts;

namespace NetinaShop.Api.Controller;

public class UserController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {

        var group = app.NewVersionedApi("Users")
            .MapGroup($"api/user")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());

        group.MapGet("info", GetUserInfoAsync)
            .WithDisplayName("GetUserInfo")
            .HasApiVersion(1.0);

        group.MapGet("", GetAllAsync)
            .WithDisplayName("GetAllUsers")
            .HasApiVersion(1.0);

        group.MapGet("{id}", GetAsync)
            .WithDisplayName("GetUser")
            .HasApiVersion(1.0);

        group.MapPost("", Post)
            .HasApiVersion(1.0);

        group.MapPut("", Put)
            .HasApiVersion(1.0);

        group.MapDelete("{id}", Delete)
            .HasApiVersion(1.0);
    }

    public async Task<IResult> GetUserInfoAsync(IUserService userService,ICurrentUserService currentUserService, CancellationToken cancellationToken)
    {

        if (!Guid.TryParse(currentUserService.UserId, out var userId))
            throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
        return TypedResults.Ok(await userService.GetUserAsync(userId, cancellationToken));
    }
    // GET:Get All Entity
    public async Task<IResult> GetAllAsync([FromQuery] int page, [FromQuery]string? phoneNumber, IUserService userService, CancellationToken cancellationToken)
        => TypedResults.Ok(await userService.GetUsersAsync(page,phoneNumber,cancellationToken));

    // GET:Get An Entity By Id
    public async Task<IResult> GetAsync(Guid id, IUserService userService, CancellationToken cancellationToken)
        => TypedResults.Ok(await userService.GetUserAsync(id,cancellationToken));

    // POST:Create Entity
    public async Task<IResult> Post([FromBody] UserActionRequestDto request, IUserService userService, CancellationToken cancellationToken)
        => TypedResults.Ok(await userService.CreateUserAsync(request,cancellationToken));

    // PUT:Update Entity
    public async Task<IResult> Put([FromBody] UserActionRequestDto request, IUserService userService, CancellationToken cancellationToken)
        => TypedResults.Ok(await userService.EditUserAsync(request,cancellationToken));

    // DELETE:Delete Entity
    public async Task<IResult> Delete(Guid id, IUserService userService, CancellationToken cancellationToken)
        => TypedResults.Ok(await userService.RemoveUserAsync(id,cancellationToken));
}