using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Application.Features.Identity.Commands.SetNurseAcceptingBookings;
using Baya.Application.Features.Identity.Commands.UploadNurseAvatar;
using Baya.Application.Features.Identity.Commands.UpsertNurseProfile;
using Baya.Application.Features.Identity.Queries.GetMyNurseProfile;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Mediator;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Baya.Web.Api.Controllers.V1;

[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[Display(Description = "The signed-in nurse's seller profile")]
public sealed class NurseProfilesController(ISender sender) : BaseController
{
    [HttpPost("[action]")]
    [ProducesOkApiResponseType<NurseProfileDto>]
    public async Task<IActionResult> Upsert(UpsertNurseProfileCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));

    [HttpPost("[action]")]
    [ProducesOkApiResponseType]
    public async Task<IActionResult> SetAcceptingBookings(SetNurseAcceptingBookingsCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));

    [HttpGet("[action]")]
    [ProducesOkApiResponseType<NurseProfileDto>]
    public async Task<IActionResult> Me(CancellationToken cancellationToken)
        => OperationResult(await sender.Send(new GetMyNurseProfileQuery(), cancellationToken));

    // Multipart image upload → stored via IObjectStorage; the returned URL is persisted on the profile.
    [HttpPost("[action]")]
    [ProducesOkApiResponseType<AvatarUploadResult>]
    public async Task<IActionResult> Avatar(IFormFile file, CancellationToken cancellationToken)
    {
        if (file is null || file.Length == 0)
            return OperationResult(Baya.Application.Models.Common.OperationResult<AvatarUploadResult>.FailureResult("No file uploaded."));

        using var buffer = new MemoryStream();
        await file.CopyToAsync(buffer, cancellationToken);
        var command = new UploadNurseAvatarCommand(buffer.ToArray(), file.ContentType, file.Length);
        return OperationResult(await sender.Send(command, cancellationToken));
    }
}
