package pl.polskalokalnie.listing;

import jakarta.validation.Valid;
import java.net.URI;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;

@RestController
@RequestMapping("/api/listings")
public class ListingController {

    private final ListingService listingService;

    public ListingController(ListingService listingService) {
        this.listingService = listingService;
    }

    @GetMapping
    public List<ListingResponse> search(
            @RequestParam(required = false) String city,
            @RequestParam(required = false) OfferType offerType,
            @RequestParam(required = false) PropertyType propertyType
    ) {
        return listingService.search(city, offerType, propertyType);
    }

    @GetMapping("/mine")
    public List<ListingResponse> mine(Authentication authentication) {
        return listingService.findMine(authentication.getName());
    }

    @GetMapping("/{id}")
    public ListingDetailResponse getById(
            @PathVariable Long id,
            @RequestParam(defaultValue = "false") boolean incrementView
    ) {
        return listingService.getById(id, incrementView);
    }

    @PostMapping
    public ResponseEntity<ListingDetailResponse> create(
            @Valid @RequestBody ListingCreateRequest request,
            Authentication authentication
    ) {
        ListingDetailResponse response = listingService.create(request, authentication.getName());
        return ResponseEntity
                .created(URI.create("/api/listings/" + response.id()))
                .body(response);
    }
}
