package com.example.dateplanner.controllers.rest;

import com.example.dateplanner.dto.PageResponse;
import com.example.dateplanner.models.entities.GalleryPost;
import com.example.dateplanner.repositories.GalleryPostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.UUID;

@RestController
@RequestMapping("/api/gallery")
@RequiredArgsConstructor
public class ApiGalleryController {

    private final GalleryPostRepository galleryPostRepository;

    @GetMapping("/posts")
    public Mono<PageResponse<GalleryPost>> getPublishedPosts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "12") int size) {

        return galleryPostRepository.countPublished()
                .flatMap(total -> galleryPostRepository.findRecentPublished(size, page * size)
                        .collectList()
                        .map(posts -> new PageResponse<>(posts, page, size, total)));
    }

    @GetMapping("/posts/latest")
    public Mono<GalleryPost> getLatestPost() {
        return galleryPostRepository.findFirstByIsPublishedTrueOrderByPublishedAtDesc();
    }

    @GetMapping("/posts/{id}")
    public Mono<GalleryPost> getPostById(@PathVariable UUID id) {
        return galleryPostRepository.findById(id)
                .filter(post -> Boolean.TRUE.equals(post.getIsPublished()));
    }
}
