using NetinaShop.Domain.Entities.Blogs;

namespace NetinaShop.Api.Controller;

public class BlogCategoryController : ICarterModule
{

    public virtual void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("BlogCategory")
            .MapGroup($"api/blog/category");

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

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

        group.MapPost("", Post)
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
            .HasApiVersion(1.0);

        group.MapPut("", Put)
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
            .HasApiVersion(1.0);

        group.MapDelete("{id}", Delete)
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
            .HasApiVersion(1.0);
    }

    // GET:Get All Entity
    public async Task<IResult> GetAllAsync([FromQuery] int? page, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        if (page != null)
        {
            return TypedResults.Ok(await repositoryWrapper.SetRepository<BlogCategory>().TableNoTracking
                .OrderByDescending(b => b.CreatedAt).Skip(page.Value * 10).Take(10)
                .Select(BlogCategoryMapper.ProjectToSDto)
                .ToListAsync(cancellationToken));
        }
        else
        {

            return TypedResults.Ok(await repositoryWrapper.SetRepository<BlogCategory>().TableNoTracking
                .OrderByDescending(b => b.CreatedAt)
                .Select(BlogCategoryMapper.ProjectToSDto)
                .ToListAsync(cancellationToken));
        }
    }

    // GET:Get An Entity By Id
    public async Task<IResult> GetAsync(Guid id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
        => TypedResults.Ok(await repositoryWrapper.SetRepository<BlogCategory>().TableNoTracking
            .Where(b => b.Id == id)
            .Select(BlogCategoryMapper.ProjectToLDto)
            .FirstOrDefaultAsync(cancellationToken));

    // POST:Create Entity
    public async Task<IResult> Post([FromBody] BlogCategorySDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = BlogCategory.Create(dto.Name,dto.Description);
        repositoryWrapper.SetRepository<BlogCategory>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }

    // PUT:Update Entity
    public async Task<IResult> Put([FromBody] BlogCategorySDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = await repositoryWrapper.SetRepository<BlogCategory>().TableNoTracking
            .FirstOrDefaultAsync(b => b.Id == dto.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Blog not found");
        var newEnt = BlogCategory.Create(dto.Name, dto.Description);
        newEnt.Id = ent.Id;
        repositoryWrapper.SetRepository<BlogCategory>().Update(newEnt);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }

    // DELETE:Delete Entity
    public async Task<IResult> Delete(Guid id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = await repositoryWrapper.SetRepository<BlogCategory>().TableNoTracking
            .FirstOrDefaultAsync(b => b.Id == id, cancellationToken);
        if (ent == null)
            throw new AppException("Blog not found");
        repositoryWrapper.SetRepository<BlogCategory>().Delete(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }
}