package com.honey.honey.controller;

import com.honey.honey.dto.*;
import com.honey.honey.model.UserA;
import com.honey.honey.security.UserContext;
import com.honey.honey.service.SupportTicketService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/support")
@RequiredArgsConstructor
public class SupportController {

    private final SupportTicketService supportTicketService;

    /**
     * Creates a new support ticket with the first message.
     */
    @PostMapping("/tickets")
    public ResponseEntity<TicketDto> createTicket(
            @Valid @RequestBody CreateTicketRequest request) {
        
        UserA user = UserContext.get();
        TicketDto ticket = supportTicketService.createTicket(
                user.getId(),
                request
        );
        
        return ResponseEntity.status(HttpStatus.CREATED).body(ticket);
    }

    /**
     * Gets ticket history for the authenticated user (last 20 tickets).
     */
    @GetMapping("/tickets")
    public ResponseEntity<List<TicketDto>> getTicketHistory() {
        
        UserA user = UserContext.get();
        List<TicketDto> tickets = supportTicketService.getTicketHistory(
                user.getId()
        );
        
        return ResponseEntity.ok(tickets);
    }

    /**
     * Gets ticket details with all messages.
     */
    @GetMapping("/tickets/{ticketId}")
    public ResponseEntity<TicketDetailDto> getTicketDetail(
            @PathVariable Long ticketId) {
        
        UserA user = UserContext.get();
        TicketDetailDto ticket = supportTicketService.getTicketDetail(
                user.getId(),
                ticketId
        );
        
        return ResponseEntity.ok(ticket);
    }

    /**
     * Adds a message to an existing ticket.
     */
    @PostMapping("/tickets/{ticketId}/messages")
    public ResponseEntity<MessageDto> addMessage(
            @PathVariable Long ticketId,
            @Valid @RequestBody CreateMessageRequest request) {
        
        UserA user = UserContext.get();
        MessageDto message = supportTicketService.addMessage(
                user.getId(),
                ticketId,
                request
        );
        
        return ResponseEntity.status(HttpStatus.CREATED).body(message);
    }

    /**
     * Closes a ticket.
     */
    @PostMapping("/tickets/{ticketId}/close")
    public ResponseEntity<Void> closeTicket(
            @PathVariable Long ticketId) {
        
        UserA user = UserContext.get();
        supportTicketService.closeTicket(
                user.getId(),
                ticketId
        );
        
        return ResponseEntity.ok().build();
    }
}

