using NetinaShop.Domain.Entities.Blogs;

namespace NetinaShop.Api.Controller;

public class BlogController : ICarterModule
{

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

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

        group.MapGet("{id}", GetAsync)
            .WithDisplayName("GetBlog")
            .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)
        => TypedResults.Ok(await repositoryWrapper.SetRepository<Blog>().TableNoTracking
            .OrderByDescending(b=>b.CreatedAt)
            .Skip(page*10).Take(10)
            .Select(BlogMapper.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<Blog>().TableNoTracking
            .Where(b=>b.Id==id)
            .Select(BlogMapper.ProjectToLDto)
            .FirstOrDefaultAsync(cancellationToken));

    // POST:Create Entity
    public async Task<IResult> Post([FromBody] BlogLDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = Blog.Create(dto.Title, dto.Content, dto.Tags, dto.ReadingTime, dto.Summery, dto.IsSuggested,dto.CategoryId);
        foreach (var file in dto.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        repositoryWrapper.SetRepository<Blog>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok(ent.AdaptToSDto());
    }

    // PUT:Update Entity
    public async Task<IResult> Put([FromBody] BlogLDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = await repositoryWrapper.SetRepository<Blog>().TableNoTracking
            .FirstOrDefaultAsync(b => b.Id == dto.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Blog not found");
        var newEnt = Blog.Create(dto.Title, dto.Content, dto.Tags, dto.ReadingTime, dto.Summery, dto.IsSuggested, dto.CategoryId);
        newEnt.Id = ent.Id;
        repositoryWrapper.SetRepository<Blog>().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<Blog>().TableNoTracking
            .FirstOrDefaultAsync(b => b.Id == id, cancellationToken);
        if (ent == null)
            throw new AppException("Blog not found");
        repositoryWrapper.SetRepository<Blog>().Delete(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }

}