package com.petshop.backend.controller;

import com.petshop.backend.dto.refund.RefundRequest;
import com.petshop.backend.dto.refund.RefundResponse;
import com.petshop.backend.dto.refund.RefundUpdateRequest;
import com.petshop.backend.entity.User;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.RefundService;
import com.petshop.backend.util.AuthenticationHelper;
import jakarta.validation.Valid;
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 java.util.List;

@RestController
@RequestMapping("/api/v1/refunds")
public class RefundController {

    private final RefundService refundService;
    private final UserRepository userRepository;

    public RefundController(RefundService refundService, UserRepository userRepository) {
        this.refundService = refundService;
        this.userRepository = userRepository;
    }

    @PostMapping
    @PreAuthorize("hasAnyRole('CUSTOMER', 'STAFF')")
    public ResponseEntity<RefundResponse> createRefund(@Valid @RequestBody RefundRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String role = authentication.getAuthorities().stream()
                .findFirst()
                .map(authority -> authority.getAuthority().replace("ROLE_", ""))
                .orElse(null);

        Long customerId = null;
        if (role != null && role.equals("CUSTOMER")) {
            User user = AuthenticationHelper.getAuthenticatedUser(userRepository);
            customerId = user.getId();
        }

        return ResponseEntity.status(HttpStatus.CREATED).body(refundService.createRefund(request, customerId));
    }

    @GetMapping
    @PreAuthorize("hasAnyRole('CUSTOMER', 'STAFF', 'ADMIN')")
    public ResponseEntity<List<RefundResponse>> getAllRefunds() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String role = authentication.getAuthorities().stream()
                .findFirst()
                .map(authority -> authority.getAuthority().replace("ROLE_", ""))
                .orElse(null);

        Long customerId = null;
        if (role != null && role.equals("CUSTOMER")) {
            User user = AuthenticationHelper.getAuthenticatedUser(userRepository);
            customerId = user.getId();
        }

        List<RefundResponse> refunds = refundService.getAllRefunds(customerId);
        return ResponseEntity.ok(refunds);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('CUSTOMER', 'STAFF', 'ADMIN')")
    public ResponseEntity<RefundResponse> getRefundById(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String role = authentication.getAuthorities().stream()
                .findFirst()
                .map(authority -> authority.getAuthority().replace("ROLE_", ""))
                .orElse(null);

        Long customerId = null;
        if (role != null && role.equals("CUSTOMER")) {
            User user = AuthenticationHelper.getAuthenticatedUser(userRepository);
            customerId = user.getId();
        }

        return ResponseEntity.ok(refundService.getRefundById(id, customerId));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('STAFF')")
    public ResponseEntity<RefundResponse> updateRefund(@PathVariable Long id, @Valid @RequestBody RefundUpdateRequest request) {
        return ResponseEntity.ok(refundService.updateRefundStatus(id, request.getStatus()));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> deleteRefund(@PathVariable Long id) {
        refundService.deleteRefund(id);
        return ResponseEntity.noContent().build();
    }
}
