using Blahblah.FlowerStory.Server.Data.Model;
using Microsoft.EntityFrameworkCore;

namespace Blahblah.FlowerStory.Server.Controller;

partial class BaseController
{
    /// <summary>
    /// 执行事务
    /// </summary>
    /// <param name="executor">执行代理</param>
    /// <param name="token">取消令牌</param>
    /// <exception cref="ArgumentNullException">执行代理为 null</exception>
    protected async Task ExecuteTransaction(Func<CancellationToken, Task> executor, CancellationToken token = default)
    {
        if (executor == null) throw new ArgumentNullException(nameof(executor));
        using var trans = await database.Database.BeginTransactionAsync(token);
        try
        {
            await executor(token);
            await trans.CommitAsync(token);
        }
        catch
        {
            await trans.RollbackAsync(token);
            throw;
        }
    }

    /// <summary>
    /// 根据 uid 获取用户对象
    /// </summary>
    /// <param name="uid">用户唯一 id</param>
    /// <returns></returns>
    protected UserItem? QueryUserItem(int uid)
    {
        return database.Users
            .FromSql($"SELECT \"uid\",\"id\",\"\" AS \"password\",\"level\",\"regdate\",\"activedate\",\"name\",\"email\",\"mobile\",NULL AS \"avatar\" FROM \"users\" WHERE \"uid\" = {uid} LIMIT 1")
            .SingleOrDefault();
    }

    /// <summary>
    /// 根据 id 获取登录使用的用户对象
    /// </summary>
    /// <param name="id">用户 id</param>
    /// <returns></returns>
    protected UserItem? QueryUserItemForAuthentication(string id)
    {
        return database.Users
            .FromSql($"SELECT \"uid\",\"id\",\"password\",0 AS \"level\",0 AS \"regdate\",\"activedate\",\"\" AS \"name\",NULL AS \"email\",NULL AS \"mobile\",NULL as \"avatar\" FROM \"users\" WHERE \"id\" = {id} LIMIT 1")
            .SingleOrDefault();
    }

    /// <summary>
    /// 获取用户头像数据
    /// </summary>
    /// <param name="uid">用户唯一 id</param>
    /// <returns></returns>
    protected byte[]? QueryUserAvatar(int uid)
    {
        return database.Database.SqlQuery<byte[]>($"SELECT \"avatar\" AS \"Value\" FROM \"users\" WHERE \"uid\" = {uid} LIMIT 1").SingleOrDefault();
    }

    /// <summary>
    /// 移除用户头像
    /// </summary>
    /// <param name="uid">用户唯一 id</param>
    /// <returns></returns>
    protected int RemoveUserAvatar(int uid)
    {
        return database.Database.ExecuteSql($"UPDATE \"users\" SET \"avatar\" = NULL WHERE \"uid\" = {uid}");
    }

    /// <summary>
    /// 添加事件项
    /// </summary>
    /// <param name="item">事件对象</param>
    /// <returns></returns>
    protected int AddRecordItem(RecordItem item)
    {
        return database.Database.ExecuteSql($"INSERT INTO \"records\"(\"uid\",\"fid\",\"eid\",\"date\",\"byuid\",\"byname\",\"memo\") VALUES({item.OwnerId},{item.FlowerId},{item.EventId},{item.DateUnixTime},{item.ByUserId},{item.ByUserName},{item.Memo})");
    }

    /// <summary>
    /// 添加照片项
    /// </summary>
    /// <param name="item">照片对象</param>
    /// <returns></returns>
    protected int AddPhotoItem(PhotoItem item)
    {
        return database.Database.ExecuteSql($"INSERT INTO \"photos\"(\"fid\",\"uid\",\"rid\",\"filetype\",\"filename\",\"path\",\"dateupload\",\"width\",\"height\") VALUES({item.FlowerId},{item.OwnerId},{item.RecordId},{item.FileType},{item.FileName},{item.Path},{item.DateUploadUnixTime},{item.Width},{item.Height})");
    }
}
