package com.example.Portfolio.Services;

import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import com.example.Portfolio.DTO.GiteaContentDto;
import com.example.Portfolio.DTO.GiteaRepoDto;

import reactor.core.publisher.Mono;

@Service
public class GiteaRepoService {

    private final WebClient webClient;

    public GiteaRepoService(WebClient webClient) {
        this.webClient = webClient;
    }

    public List<GiteaRepoDto> getRepositories(String username) {
        return webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/users/{user}/repos")
                        .queryParam("visibility", "public")
                        .build(username))
                .retrieve()
                .bodyToFlux(GiteaRepoDto.class)
                .collectList()
                .block();
    }

    public GiteaRepoDto getRepository(String owner, String repo) {

        return webClient.get()
                .uri("/repos/{owner}/{repo}", owner, repo)
                .retrieve()
                .onStatus(
                        status -> status.value() == 404,
                        response -> Mono.error(
                                new IllegalArgumentException("Repository not found: " + repo)))
                .bodyToMono(GiteaRepoDto.class)
                .block();
    }

    public String getRawFile(
            String owner,
            String repo,
            String branch,
            String path) {

        return webClient.get()
                .uri("/repos/{o}/{r}/raw/{b}/{p}",
                        owner, repo, branch, path)
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }

    public List<String> getScreenshots(String owner, String repo) {
        return webClient.get()
                .uri("/repos/{o}/{r}/contents/screenshots", owner, repo)
                .retrieve()
                .bodyToFlux(GiteaContentDto.class)
                .filter(item -> item.type().equals("file"))
                .map(GiteaContentDto::download_url)
                .toStream()
                .toList();
    }

}
