using adas_core.Application.Exceptions;
using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Attributes;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.MongoModels;
using adas_core.Logging;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;

namespace adas_core.Controllers;

[Route("notices")]
public class NoticeController : ControllerBase
{
    private readonly INoticeService _noticeService;


    public NoticeController(INoticeService noticeService)
    {
        LogExecutionContext.TrySetTraceIdentifier(Guid.NewGuid().ToString(), true);

        _noticeService = noticeService;
    }


    [HttpGet]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> GetAllNotices()
    {
        var result = await _noticeService.GetNoticesAsync();
        return Ok(result);
    }

    [HttpGet("{type}/type")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> GetNoticesByType(string type)
    {
        var result = await _noticeService.GetNoticeByTypeAsync(type);
        return Ok(result);
    }

    [HttpGet("{id}")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> GetNoticesById(string id)
    {
        var result = await _noticeService.GetNoticeByTypeAsync(id);

        return Ok(result);
    }

    [HttpPost]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> InsertNotice([FromBody] Notice notice, [FromHeader] string displayId)
    {
        if (!ObjectId.TryParse(displayId, out var displayIdParsed))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);
        notice.DisplayId = displayIdParsed;
        var result = await _noticeService.InsertNotice(notice);
        return Ok(result);
    }

    [HttpPut("{id}")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> UpdateNotice(string id, [FromBody] Notice notice)
    {
        if (!ObjectId.TryParse(id, out var noticeId))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);
        notice.Id = noticeId;
        await _noticeService.UpdateNoticeAsync(notice);
        return Ok();
    }

    [HttpDelete("{id}")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> DeleteNotice(string id)
    {
        if (!ObjectId.TryParse(id, out var noticeId))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);
        await _noticeService.DeleteNoticeByIdAsync(noticeId);
        return Ok();
    }
}