namespace MyOffice.Web.Controllers;

using AutoMapper;
using Core;
using Core.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Models.Account;
using Models.Item;
using Models.Motion;
using MyOffice.Web.Infrastructure.Attributes;
using Services.Account;
using Services.Account.Domain;
using Services.Item;

[Authorize]
[DefaultFromBody]
public class AccountController : BaseApiController
{
	private readonly ILogger<AccountController> _logger;
	private readonly IMapper _mapper;
	private readonly AccountService _accountService;
	private readonly ItemService _itemService;

	public AccountController(
		ILogger<AccountController> logger,
		IMapper mapper,
		AccountService accountService,
		ItemService itemService
	)
	{
		_logger = logger;
		_mapper = mapper;
		_accountService = accountService;
		_itemService = itemService;
	}

	public ObjectResult AccountsGet(string category)
	{
		var list = _accountService.GetByCategoryDetailed(UserId, category!.AsGuid());

		return OkResponse(_mapper.Map<List<AccountDetailedViewModel>>(list.OrderBy(x => x.Account.Name).ToList()));
	}

	public ObjectResult AccountGet(string id)
	{
		var exec = _accountService.GetByIdDetailed(UserId, id!.AsGuid());

		switch (exec.Status)
		{
			case GeneralExecStatus.not_found:
			case GeneralExecStatus.failure:
				return ProblemBadResponse("Account not found.");

			case GeneralExecStatus.success:
				return OkResponse(_mapper.Map<AccountDetailedViewModel>(exec.Result));

			default:
				throw new NotSupportedException(exec.Status.ToString());
		}
	}

	public ObjectResult MotionsGet(string id, [FromQuery] MotionsGetRequest request)
	{
		var exec = _accountService.GetMotions(UserId, id!.AsGuid(), request.From.StartOfDay(), request.To.EndOfDay());

		switch (exec.Status)
		{
			case GeneralExecStatus.not_found:
			case GeneralExecStatus.failure:
				return ProblemBadResponse("Account not found.");

			case GeneralExecStatus.success:
				return OkResponse(_mapper.Map<List<MotionViewModel>>(exec.Result!));

			default:
				throw new NotSupportedException(exec.Status.ToString());
		}
	}

	public object MotionsPost(string id, MotionRequest motion)
	{
		var exec = _accountService.MotionAdd(UserId, id.AsGuid(), _mapper.Map<MotionAddUpdate>(motion));

		switch (exec.Status)
		{
			case MotionAddStatus.account_not_found:
				return ProblemBadResponse("Account not found.");
			case MotionAddStatus.failure:
				return ProblemBadResponse("Adding motion failed.");
			case MotionAddStatus.success:
				return _mapper.Map<MotionViewModel[]>(exec.Result!);

			default:
				throw new NotSupportedException(exec.Status.ToString());
		}
	}

	public ObjectResult MotionsPut(string id, string motionId, MotionRequest motion)
	{
		var exec = _accountService.MotionUpdate(UserId, id.AsGuid(), motionId.AsGuid(), _mapper.Map<MotionAddUpdate>(motion));

		switch (exec.Status)
		{
			case MotionUpdateStatus.not_found:
				return ProblemBadResponse("Motion not found.");
			case MotionUpdateStatus.failure:
				return ProblemBadResponse("Updating motion failed.");
			case MotionUpdateStatus.success:
				return OkResponse(_mapper.Map<List<MotionViewModel>>(exec.Result!));

			default:
				throw new NotSupportedException(exec.Status.ToString());
		}
	}

	public ObjectResult MotionsDelete(string id, string motionId)
	{
		var exec = _accountService.MotionRemove(UserId, id.AsGuid(), motionId.AsGuid());

		switch (exec.Status)
		{
			case MotionDeleteStatus.not_found:
				return ProblemBadResponse("Motion not found.");
			case MotionDeleteStatus.failure:
				return ProblemBadResponse("Deliting motion failed.");
			case MotionDeleteStatus.success:
				return OkResponse(_mapper.Map<MotionViewModel>(exec.Result!));

			default:
				throw new NotSupportedException(exec.Status.ToString());
		}
	}

	public ObjectResult FindItems(string term)
	{
		var itemsDto = _itemService.FindItems(UserId, term);

		var items = _mapper.Map<List<ItemViewModel>>(itemsDto);

		if (term.StartsWith("+") && term.Length > 1)
		{
			var accounts = _accountService
				.FindAccounts(UserId, term.Substring(1))
				.OrderByDescending(x => x.Name);

			foreach (var account in accounts)
			{
				var accountName = $"+{account.Name}";
				var item = items.FirstOrDefault(x => x.Name.IsPresent() && x.Name!.Length > 1 && x.Name.Substring(1) == accountName);

				if (item == null)
				{
					items.Add(new ItemViewModel
					{
						Name = accountName,
						AccountId = account.Id.ToShort(),
					});
				}
				else
				{
					item.AccountId = account.Id.ToShort();
				}
			}
		}

		return OkResponse(_mapper
			.Map<List<ItemViewModel>>(items)
			.OrderBy(x => x.AccountId)
			.ThenBy(x => x.Name)
		);
	}
}