using API.Database;
using API.Models.Internal.User;
using Microsoft.EntityFrameworkCore;

namespace API.Repository.RegistrationKeyRepo;

public class RegistrationKeyService : IRegistrationKeyService
{
    private ApplicationDbContext _context;

    public RegistrationKeyService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<List<RegistrationKey>> GetAllAsync()
    {
        var allKeys = await _context.RegistrationKeys.ToListAsync();

        return allKeys;
    }

    public async Task<RegistrationKey?> GetAsync(string id)
    {
        return await _context.RegistrationKeys.FindAsync(id);
    }

    public async Task<RegistrationKey> CreateAsync(RegistrationKeyIngoing key)
    {
        var internalKey = key.ToInternalFromIngoing();

        await _context.RegistrationKeys.AddAsync(internalKey);
        await _context.SaveChangesAsync();

        return internalKey;
    }

    public async Task<RegistrationKey?> DeleteAsync(string id)
    {
        var key = await _context.RegistrationKeys.FirstOrDefaultAsync(x => x.Id == id);

        if (key == null)
        {
            return null;
        }

        _context.RegistrationKeys.Remove(key);
        await _context.SaveChangesAsync();

        return key;
    }

    public async Task<int> DeleteOldRegistrationKeysAsync(int x)
    {
        if (x <= 0)
        {
            return 0;
        }

        var cutoff = DateTime.UtcNow.AddDays(-x);

        var oldKeys = await _context.RegistrationKeys
            .Where(k => k.Created < cutoff)
            .ToListAsync();

        if (oldKeys.Count == 0)
        {
            return 0;
        }

        _context.RegistrationKeys.RemoveRange(oldKeys);
        await _context.SaveChangesAsync();

        return oldKeys.Count;
    }
}