package com.tasteby.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tasteby.domain.Channel;
import com.tasteby.security.AuthUtil;
import com.tasteby.service.CacheService;
import com.tasteby.service.ChannelService;
import com.tasteby.service.YouTubeService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/channels")
public class ChannelController {

    private final ChannelService channelService;
    private final YouTubeService youtubeService;
    private final CacheService cache;
    private final ObjectMapper objectMapper;

    public ChannelController(ChannelService channelService, YouTubeService youtubeService,
                             CacheService cache, ObjectMapper objectMapper) {
        this.channelService = channelService;
        this.youtubeService = youtubeService;
        this.cache = cache;
        this.objectMapper = objectMapper;
    }

    @GetMapping
    public List<Channel> list() {
        String key = cache.makeKey("channels");
        String cached = cache.getRaw(key);
        if (cached != null) {
            try {
                return objectMapper.readValue(cached, new TypeReference<List<Channel>>() {});
            } catch (Exception ignored) {}
        }
        var result = channelService.findAllActive();
        cache.set(key, result);
        return result;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Map<String, Object> create(@RequestBody Map<String, String> body) {
        AuthUtil.requireAdmin();
        String channelId = body.get("channel_id");
        String channelName = body.get("channel_name");
        String titleFilter = body.get("title_filter");
        try {
            String id = channelService.create(channelId, channelName, titleFilter);
            cache.flush();
            return Map.of("id", id, "channel_id", channelId);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().toUpperCase().contains("UQ_CHANNELS_CID")) {
                throw new ResponseStatusException(HttpStatus.CONFLICT, "Channel already exists");
            }
            throw e;
        }
    }

    @PostMapping("/{channelId}/scan")
    public Map<String, Object> scan(@PathVariable String channelId,
                                    @RequestParam(defaultValue = "false") boolean full) {
        AuthUtil.requireAdmin();
        var result = youtubeService.scanChannel(channelId, full);
        if (result == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Channel not found");
        }
        cache.flush();
        return result;
    }

    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable String id, @RequestBody Map<String, Object> body) {
        AuthUtil.requireAdmin();
        Integer sortOrder = body.get("sort_order") != null ? ((Number) body.get("sort_order")).intValue() : null;
        channelService.update(id, (String) body.get("description"), (String) body.get("tags"), sortOrder);
        cache.flush();
        return Map.of("ok", true);
    }

    @DeleteMapping("/{channelId}")
    public Map<String, Object> delete(@PathVariable String channelId) {
        AuthUtil.requireAdmin();
        if (!channelService.deactivate(channelId)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Channel not found");
        }
        cache.flush();
        return Map.of("ok", true);
    }
}
