using Netina.Domain.Dtos.ResponseDtos;
using Netina.Domain.Enums;

namespace Netina.Api.Controllers;

public class FileController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("File")
            .MapGroup("api/file");

        group.MapGet("", GetFilesAsync)
            .WithDisplayName("Get Files")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser().RequireClaim(CustomClaimType.Permission, ApplicationPermission.ManageFiles, ApplicationPermission.ViewFiles))
            .HasApiVersion(1.0);

        group.MapPost("", UploadFileAsync)
            .WithDisplayName("Upload File")
            .HasApiVersion(1.0);

        group.MapPost("/ckeditor", UploadCkEditorFileAsync)
            .WithDisplayName("Upload CkEditor File")
            .AllowAnonymous()
            .DisableAntiforgery()
            .HasApiVersion(1.0);

    }

    public async Task<IResult> UploadCkEditorFileAsync(IFormFile upload, [FromServices] IHttpContextAccessor httpContextAccessor, [FromServices] IStorageService storageService, IUploadFileService uploadFileService, CancellationToken cancellationToken)
    {
        try
        {
            if (httpContextAccessor.HttpContext?.Request?.Headers is { } dictionary && dictionary.TryGetValue("Authorization", out StringValues value))
            {
                if (value.ToString() != "xuwp4KzU1/YBoevpzgH0cz8+zLKQ+EOaYXeo4JtRxmVIuN7Hqxz97oQ398tNX68+")
                    throw new Exception("ارسال فایل از طرف شما معتبر نمی باشد");

                using var stream = new MemoryStream();
                await upload.CopyToAsync(stream, cancellationToken);
                var uploadRequest = new FileUploadRequest
                {
                    FileName = upload.FileName,
                    ContentType = upload.ContentType,
                    FileUploadType = FileUploadType.Image,
                    StringBaseFile = Convert.ToBase64String(stream.ToArray())
                };
                var fileUrl = await uploadFileService.UploadImageAsync(uploadRequest);
                return TypedResults.Ok(new CkEditorFileUploadResponseDto { url = fileUrl.FileUrl });
            }
            throw new Exception("ارسال فایل از طرف شما معتبر نمی باشد");
        }
        catch (Exception e)
        {
            var errorMessage = new
            {
                message = e.Message
            };
            var errorResponse = new
            {
                error = errorMessage
            };
            return TypedResults.BadRequest(errorResponse);
        }
    }

    public async Task<IResult> GetFilesAsync([FromQuery]StorageFileType? fileType,[FromServices] IStorageService storageService, CancellationToken cancellationToken)
        => TypedResults.Ok(await storageService.GetStorageFiles(fileType: fileType ?? StorageFileType.Image));

    public async Task<IResult> UploadFileAsync([FromBody] FileUploadRequest uploadRequest, [FromServices] IUploadFileService uploadFileService, CancellationToken cancellationToken)
    {
        return TypedResults.Ok(await uploadFileService.UploadImageAsync(uploadRequest));
    }
}