namespace AAIntegration.SimmonsBank.API.Controllers;

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using AAIntegration.SimmonsBank.API.Models.Transactions;
using AAIntegration.SimmonsBank.API.Services;
using AAIntegration.SimmonsBank.API.Config;
using System.Runtime.InteropServices;
using AAIntegration.SimmonsBank.API.Entities;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

[Authorize]
[ApiController]
[Route("[controller]")]
public class TransactionsController : ControllerBase
{
    private ITransactionService _transactionService;
    private IUserService _userService;
    private IMapper _mapper;
    private readonly AppSettings _appSettings;
    private readonly ILogger<TransactionsController> _logger;

    public TransactionsController(
        ITransactionService transactionService,
        IUserService userService,
        IMapper mapper,
        IOptions<AppSettings> appSettings,
        ILogger<TransactionsController> logger)
    {
        _transactionService = transactionService;
        _userService = userService;
        _mapper = mapper;
        _appSettings = appSettings.Value;
        _logger = logger;
    }

    [HttpGet]
    public IActionResult GetAll(int? accountId = null)
    {
        List<TransactionDto> transactionDtos = new List<TransactionDto>();

        foreach (Transaction tran in _transactionService.GetAll(this.GetCurrentUserId()))
        {
            if (accountId.HasValue
            && (tran.DebitAccount == null || tran.DebitAccount.Id != accountId)
            && (tran.CreditAccount == null || tran.CreditAccount.Id != accountId))
                continue;

            transactionDtos.Add(_mapper.Map<Transaction, TransactionDto>(tran));
        }

        // Sort by Date
        transactionDtos.Sort((t1, t2) => t2.Date.CompareTo(t1.Date));

        return Ok(transactionDtos);
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        Transaction tran = _transactionService.GetById(id, this.GetCurrentUserId());
        return Ok(_mapper.Map<Transaction, TransactionDto>(tran));
    }

    [HttpPost("BulkAdd")]
    public IActionResult BulkCreate([FromBody]List<TransactionCreate> model)
    {
        List<Transaction> trans = _transactionService.BulkCreate(model, this.GetCurrentUserId()).ToList();
        return Ok(new { message = $"{trans.Count()} transaction(s) created." });
    }

    [HttpPost]
    public IActionResult Create([FromBody]TransactionCreate model)
    {
        Transaction tran = _transactionService.Create(model, this.GetCurrentUserId());
        return Ok(new { message = $"transaction '{tran.Description}' created with id '{tran.Id}'." });
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, [FromBody]TransactionUpdateRequest model)
    {
        _transactionService.Update(id, model, this.GetCurrentUserId());
        return Ok(new { message = $"transaction with id '{id}' updated" });
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        _transactionService.Delete(id, this.GetCurrentUserId());
        return Ok(new { message = "transaction deleted" });
    }

    // Helpers

    private int GetCurrentUserId()
    {
        string apiKey = User.FindFirstValue(ClaimTypes.NameIdentifier);

        if (apiKey is null)
            _logger.LogInformation($"ApiKey: is null");

        _logger.LogInformation($"apiKey: {apiKey}");

        return _userService.GetUser(apiKey).Id;
    }
}