using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RR3CommunityServer.Data;
using static RR3CommunityServer.Data.RR3DbContext;

namespace RR3CommunityServer.Pages;

public class UsersModel : PageModel
{
    private readonly RR3DbContext _context;

    public UsersModel(RR3DbContext context)
    {
        _context = context;
    }

    public List<User> Users { get; set; } = new();
    public string? SearchQuery { get; set; }

    public async Task OnGetAsync(string? search)
    {
        SearchQuery = search;
        
        var query = _context.Users.AsQueryable();
        
        if (!string.IsNullOrEmpty(search))
        {
            query = query.Where(u => u.SynergyId.Contains(search) || u.DeviceId.Contains(search));
        }
        
        Users = await query
            .OrderByDescending(u => u.CreatedAt)
            .ToListAsync();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int userId)
    {
        var user = await _context.Users.FindAsync(userId);
        if (user != null)
        {
            _context.Users.Remove(user);
            await _context.SaveChangesAsync();
        }
        
        return RedirectToPage();
    }
}
