// Copyright (C) 2021-present sam (starshines.gay)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

using Catalogger.Backend.Database.Redis;

namespace Catalogger.Backend.Api;

public class ApiCache(RedisService redisService)
{
    private static string UserKey(string id) => $"api-user:{id}";

    private static string GuildsKey(string userId) => $"api-user-guilds:{userId}";

    public async Task<User?> GetUserAsync(string id) =>
        await redisService.GetAsync<User>(UserKey(id));

    public async Task SetUserAsync(User user) =>
        await redisService.SetAsync(UserKey(user.Id), user, expiry: TimeSpan.FromHours(1));

    public async Task ExpireUserAsync(string id) =>
        await redisService.GetDatabase().KeyDeleteAsync([UserKey(id), GuildsKey(id)]);

    public async Task<List<Guild>?> GetGuildsAsync(string userId) =>
        await redisService.GetAsync<List<Guild>>(GuildsKey(userId));

    public async Task SetGuildsAsync(string userId, List<Guild> guilds) =>
        await redisService.SetAsync(GuildsKey(userId), guilds, expiry: TimeSpan.FromHours(1));
}
