using Microsoft.EntityFrameworkCore;
using TodoTicketApp.Data;
using TodoTicketApp.Models;

namespace TodoTicketApp.Services;

public class SqliteTicketService : ITicketService
{
    private readonly AppDbContext _context;

    public SqliteTicketService(AppDbContext context)
    {
        _context = context;
    }

    public void AddTicket(Ticket ticket)
    {
        _context.Tickets.Add(ticket);
        _context.SaveChanges();
    }

    public IEnumerable<Ticket> GetPendingTickets()
    {
        // Wichtig: .Include(t => t.Comments) sorgt dafür, dass die Kommentare mitgeladen werden
        return _context.Tickets
            .Include(t => t.Comments)
            .Where(t => !t.IsCompleted)
            .OrderBy(t => t.IsWaitingForFeedback)
            .ThenByDescending(t => t.Priority)
            .ThenBy(t => t.CreatedAt)
            .ToList();
    }

    public Ticket? GetTicketById(Guid id)
    {
        return _context.Tickets
            .Include(t => t.Comments)
            .FirstOrDefault(t => t.Id == id);
    }

    public Ticket? GetNextTicket()
    {
        return GetPendingTickets().FirstOrDefault();
    }

    public void CompleteTicket(Guid id)
    {
        var ticket = _context.Tickets.FirstOrDefault(t => t.Id == id);
        if (ticket != null)
        {
            ticket.IsCompleted = true;
            _context.SaveChanges();
        }
    }

    public void AddComment(Guid ticketId, TicketComment comment)
    {
        comment.TicketId = ticketId;
        _context.Comments.Add(comment);
        _context.SaveChanges();
    }

    public void UpdateTicket(Ticket ticket)
    {
        _context.Tickets.Update(ticket);
        _context.SaveChanges();
    }
}