namespace Fast.Web.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class SystemPasswordsController : ODataController
{
    private readonly MyDbContext db;
    private readonly AuthorizationHelper authHelper;

    public SystemPasswordsController(MyDbContext context)
    {
        db = context;
        authHelper = new AuthorizationHelper(Main.IsAuthenticationEnabled);
    }

    [Permission("System Passwords", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetRequiredData()
    {
        var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "System Passwords", PermissionType.Modify);

        var result = new { hasModifyPermission };
        return Ok(result);
    }

    [Permission("System Passwords", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetDetail()
    {
        var passwords = new SystemPasswordsDetail
        {
            DealAlter = Encryption.Decrypt((await db.Passwords.Where(x => x.Name == "DealChange").FirstAsync()).Pass ?? ""),
            ArapAlter = Encryption.Decrypt((await db.Passwords.Where(x => x.Name == "ARAPChange").FirstAsync()).Pass ?? ""),
            OverdueAlter = Encryption.Decrypt((await db.Passwords.Where(x => x.Name == "OverdueChange").FirstAsync()).Pass ?? ""),
            PdfEdit = Encryption.Decrypt((await db.Passwords.Where(x => x.Name == "PDFPassword").FirstAsync()).Pass ?? ""),
            AccountingExport = Encryption.Decrypt((await db.Passwords.Where(x => x.Name == "AccountingExportPassword").FirstAsync()).Pass ?? "")
        };

        return Ok(passwords);
    }


    [Permission("System Passwords", PermissionType.Modify)]
    [Route("[action]")]
    public async Task<IActionResult> SaveDetail(SystemPasswordsDetail passwords)
    {
        (await db.Passwords.Where(x => x.Name == "DealChange").FirstAsync()).Pass = Encryption.Encrypt(passwords.DealAlter);
        (await db.Passwords.Where(x => x.Name == "ARAPChange").FirstAsync()).Pass = Encryption.Encrypt(passwords.ArapAlter);
        (await db.Passwords.Where(x => x.Name == "OverdueChange").FirstAsync()).Pass = Encryption.Encrypt(passwords.OverdueAlter);
        (await db.Passwords.Where(x => x.Name == "PDFPassword").FirstAsync()).Pass = Encryption.Encrypt(passwords.PdfEdit);
        (await db.Passwords.Where(x => x.Name == "AccountingExportPassword").FirstAsync()).Pass = Encryption.Encrypt(passwords.AccountingExport);

        await db.SaveChangesAsync();

        return Ok();
    }
}
