package sn.ladoum.bergerie.auth;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Valid;
import jakarta.validation.Validator;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sn.ladoum.bergerie.auth.dto.AuthResponse;
import sn.ladoum.bergerie.auth.dto.LoginRequest;
import sn.ladoum.bergerie.auth.dto.RegisterRequest;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final ObjectMapper objectMapper;
    private final Validator validator;

    @PostMapping("/login")
    public AuthResponse login(@Valid @RequestBody LoginRequest request) {
        return authService.login(request);
    }

    @PostMapping(value = "/register", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AuthResponse register(@RequestPart("data") String dataJson,
                                 @RequestParam("logo") MultipartFile logo) {
        RegisterRequest request;
        try {
            request = objectMapper.readValue(dataJson, RegisterRequest.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Données d'inscription invalides : " + e.getOriginalMessage());
        }
        var violations = validator.validate(request);
        if (!violations.isEmpty()) {
            String msg = violations.stream()
                    .map(v -> v.getPropertyPath() + " : " + v.getMessage())
                    .collect(Collectors.joining(" ; "));
            throw new IllegalArgumentException(msg);
        }
        return authService.register(request, logo);
    }
}
