// 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.Models;
using Dapper;
using Remora.Rest.Core;

namespace Catalogger.Backend.Database.Repositories;

public class WatchlistRepository(ILogger logger, DatabaseConnection conn)
    : IDisposable,
        IAsyncDisposable
{
    private readonly ILogger _logger = logger.ForContext<WatchlistRepository>();

    public async Task<List<Watchlist>> GetGuildWatchlistAsync(Snowflake guildId) =>
        (
            await conn.QueryAsync<Watchlist>(
                "select * from watchlists where guild_id = @GuildId",
                new { GuildId = guildId.Value }
            )
        ).ToList();

    public async Task<Watchlist?> GetEntryAsync(Snowflake guildId, Snowflake userId) =>
        await conn.QueryFirstOrDefaultAsync<Watchlist>(
            "select * from watchlists where guild_id = @GuildId and user_id = @UserId",
            new { GuildId = guildId.Value, UserId = userId.Value }
        );

    public async Task<Watchlist> CreateEntryAsync(
        Snowflake guildId,
        Snowflake userId,
        Snowflake moderatorId,
        string reason
    ) =>
        await conn.QueryFirstAsync<Watchlist>(
            """
            insert into watchlists (guild_id, user_id, added_at, moderator_id, reason)
            values (@GuildId, @UserId, now(), @ModeratorId, @Reason)
            on conflict (guild_id, user_id) do update
            set moderator_id = @ModeratorId, added_at = now(), reason = @Reason
            returning *
            """,
            new
            {
                GuildId = guildId.Value,
                UserId = userId.Value,
                ModeratorId = moderatorId.Value,
                Reason = reason,
            }
        );

    public async Task<bool> RemoveEntryAsync(Snowflake guildId, Snowflake userId) =>
        (
            await conn.ExecuteAsync(
                "delete from watchlists where guild_id = @GuildId and user_id = @UserId",
                new { GuildId = guildId.Value, UserId = userId.Value }
            )
        ) != 0;

    /// <summary>
    /// Bulk imports an array of watchlist entries.
    /// The GuildId property in the Watchlist object is ignored.
    /// </summary>
    public async Task ImportWatchlistAsync(Snowflake guildId, IEnumerable<Watchlist> watchlist)
    {
        await using var tx = await conn.BeginTransactionAsync();
        foreach (var entry in watchlist)
        {
            await conn.ExecuteAsync(
                """
                insert into watchlists (guild_id, user_id, added_at, moderator_id, reason)
                values (@GuildId, @UserId, @AddedAt, @ModeratorId, @Reason)
                on conflict (guild_id, user_id) do update
                set added_at = @AddedAt,
                    moderator_id = @ModeratorId,
                    reason = @Reason
                """,
                new
                {
                    GuildId = guildId.Value,
                    entry.UserId,
                    entry.AddedAt,
                    entry.ModeratorId,
                    entry.Reason,
                },
                transaction: tx
            );
        }

        await tx.CommitAsync();
    }

    public void Dispose()
    {
        conn.Dispose();
        GC.SuppressFinalize(this);
    }

    public async ValueTask DisposeAsync()
    {
        await conn.DisposeAsync();
        GC.SuppressFinalize(this);
    }
}
