package com.example.skychasemk.services;

import com.example.skychasemk.dto.SupportTicketDTO;
import com.example.skychasemk.model.SupportTicket;
import com.example.skychasemk.repository.SupportTicketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import static com.example.skychasemk.model.SupportTicket.TicketStatus.OPEN;

@Service
public class SupportTicketService {

    @Autowired
    private SupportTicketRepository supportTicketRepository;


    public SupportTicketService(SupportTicketRepository repository){
        this.supportTicketRepository=repository;
    }
    public List<SupportTicket> getAllTickets() {
        return supportTicketRepository.findTickets();
    }
    public List<SupportTicket> getResolvedTickets() {
        return supportTicketRepository.findResolvedTickets();
    }

    public Optional<SupportTicket> getTicketById(Integer ticketID) {
        return supportTicketRepository.findById(ticketID);
    }

    @PostMapping
    public SupportTicket createTicket(@RequestBody SupportTicketDTO dto) {
        SupportTicket ticket = new SupportTicket();
        ticket.setDateCreated(LocalDate.now());
        ticket.setStatus(OPEN);
        ticket.setSubject("Issue Opened");
        ticket.setDescription(dto.getDescription());

        return supportTicketRepository.save(ticket);
    }

    public SupportTicket save(SupportTicket ticket) {
        return supportTicketRepository.save(ticket);
    }

    public SupportTicket updateTicket(Integer id, SupportTicket.TicketStatus newStatus) {
        return supportTicketRepository.findById(id)
                .map(ticket -> {
                    ticket.setStatus(newStatus);
                    if (newStatus == SupportTicket.TicketStatus.RESOLVED) {
                        ticket.setDateResolved(LocalDate.now());
                    }
                    return supportTicketRepository.save(ticket);
                })
                .orElseThrow(() -> new RuntimeException("Ticket not found"));
    }


}

