package com.honey.honey.controller;

import com.honey.honey.dto.QuickAnswerCreateRequest;
import com.honey.honey.dto.QuickAnswerDto;
import com.honey.honey.model.Admin;
import com.honey.honey.model.QuickAnswer;
import com.honey.honey.repository.AdminRepository;
import com.honey.honey.repository.QuickAnswerRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/quick-answers")
@RequiredArgsConstructor
@PreAuthorize("hasAnyRole('ADMIN')")
public class QuickAnswerController {

    private final QuickAnswerRepository quickAnswerRepository;
    private final AdminRepository adminRepository;

    /**
     * Get current admin from authentication context
     */
    private Admin getCurrentAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return adminRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("Admin not found: " + username));
    }

    /**
     * Get all quick answers for the current admin
     */
    @GetMapping
    public ResponseEntity<List<QuickAnswerDto>> getQuickAnswers() {
        Admin admin = getCurrentAdmin();
        List<QuickAnswer> quickAnswers = quickAnswerRepository.findByAdminIdOrderByCreatedAtDesc(admin.getId());
        List<QuickAnswerDto> dtos = quickAnswers.stream()
                .map(qa -> new QuickAnswerDto(
                        qa.getId(),
                        qa.getText(),
                        qa.getCreatedAt(),
                        qa.getUpdatedAt()
                ))
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    /**
     * Create a new quick answer for the current admin
     */
    @PostMapping
    public ResponseEntity<QuickAnswerDto> createQuickAnswer(@Valid @RequestBody QuickAnswerCreateRequest request) {
        Admin admin = getCurrentAdmin();
        
        if (request.getText() == null || request.getText().trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        QuickAnswer quickAnswer = QuickAnswer.builder()
                .admin(admin)
                .text(request.getText().trim())
                .build();

        QuickAnswer saved = quickAnswerRepository.save(quickAnswer);
        QuickAnswerDto dto = new QuickAnswerDto(
                saved.getId(),
                saved.getText(),
                saved.getCreatedAt(),
                saved.getUpdatedAt()
        );
        return ResponseEntity.status(HttpStatus.CREATED).body(dto);
    }

    /**
     * Update a quick answer (only if it belongs to the current admin)
     */
    @PutMapping("/{id}")
    public ResponseEntity<QuickAnswerDto> updateQuickAnswer(
            @PathVariable Integer id,
            @Valid @RequestBody QuickAnswerCreateRequest request) {
        Admin admin = getCurrentAdmin();
        QuickAnswer quickAnswer = quickAnswerRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Quick answer not found"));

        // Verify that the quick answer belongs to the current admin
        if (!quickAnswer.getAdmin().getId().equals(admin.getId())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        if (request.getText() == null || request.getText().trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        quickAnswer.setText(request.getText().trim());
        QuickAnswer saved = quickAnswerRepository.save(quickAnswer);
        
        QuickAnswerDto dto = new QuickAnswerDto(
                saved.getId(),
                saved.getText(),
                saved.getCreatedAt(),
                saved.getUpdatedAt()
        );
        return ResponseEntity.ok(dto);
    }

    /**
     * Delete a quick answer (only if it belongs to the current admin)
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteQuickAnswer(@PathVariable Integer id) {
        Admin admin = getCurrentAdmin();
        QuickAnswer quickAnswer = quickAnswerRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Quick answer not found"));

        // Verify that the quick answer belongs to the current admin
        if (!quickAnswer.getAdmin().getId().equals(admin.getId())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        quickAnswerRepository.delete(quickAnswer);
        return ResponseEntity.noContent().build();
    }
}

