package com.ycwl.basic.controller.mobile;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.model.mobile.video.dto.VideoViewPermissionDTO;
import com.ycwl.basic.model.pc.video.resp.VideoRespVO;
import com.ycwl.basic.model.task.req.VideoInfoReq;
import com.ycwl.basic.repository.VideoRepository;
import com.ycwl.basic.service.mobile.VideoViewPermissionService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Slf4j
@RestController
@RequestMapping("/api/mobile/video/v1")
public class AppVideoController {

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private VideoViewPermissionService videoViewPermissionService;

    @PostMapping("/{videoId}/updateMeta")
    public void updateMeta(@PathVariable("videoId") Long videoId, @RequestBody VideoInfoReq req) {
        videoRepository.updateMeta(videoId, req);
    }

    /**
     * 记录用户查看视频并返回权限信息
     *
     * @param videoId 视频ID
     * @return 查看权限信息
     */
    @PostMapping("/{videoId}/recordView")
    public ApiResponse<VideoViewPermissionDTO> recordView(@PathVariable("videoId") Long videoId) {
        try {
            String userIdStr = BaseContextHandler.getUserId();
            if (userIdStr == null || userIdStr.isEmpty()) {
                log.warn("用户未登录，无法记录查看: videoId={}", videoId);
                return ApiResponse.fail("用户未登录");
            }

            Long userId = Long.valueOf(userIdStr);
            log.debug("记录用户查看视频: userId={}, videoId={}", userId, videoId);

            VideoViewPermissionDTO permission = videoViewPermissionService.checkAndRecordView(userId, videoId);
            return ApiResponse.success(permission);

        } catch (NumberFormatException e) {
            log.error("用户ID格式错误: userId={}, videoId={}", BaseContextHandler.getUserId(), videoId, e);
            return ApiResponse.fail("用户信息无效");
        } catch (Exception e) {
            log.error("记录用户查看视频失败: videoId={}", videoId, e);
            return ApiResponse.fail("记录查看失败，请稍后重试");
        }
    }

    /**
     * 检查用户查看权限（不记录查看次数）
     *
     * @param videoId 视频ID
     * @return 查看权限信息
     */
    @GetMapping("/{videoId}/checkPermission")
    public ApiResponse<VideoViewPermissionDTO> checkPermission(@PathVariable("videoId") Long videoId) {
        try {
            String userIdStr = BaseContextHandler.getUserId();
            if (userIdStr == null || userIdStr.isEmpty()) {
                log.warn("用户未登录，无法查看权限: videoId={}", videoId);
                return ApiResponse.fail("用户未登录");
            }

            Long userId = Long.valueOf(userIdStr);
            log.debug("检查用户查看权限: userId={}, videoId={}", userId, videoId);

            VideoViewPermissionDTO permission = videoViewPermissionService.checkViewPermission(userId, videoId);
            return ApiResponse.success(permission);

        } catch (NumberFormatException e) {
            log.error("用户ID格式错误: userId={}, videoId={}", BaseContextHandler.getUserId(), videoId, e);
            return ApiResponse.fail("用户信息无效");
        } catch (Exception e) {
            log.error("检查用户查看权限失败: videoId={}", videoId, e);
            return ApiResponse.fail("权限检查失败，请稍后重试");
        }
    }

    /**
     * 通过faceId和templateId（可选）查询最新的视频记录
     *
     * @param faceId 人脸ID
     * @param templateId 模板ID（可选）
     * @return 最新的视频记录
     */
    @GetMapping("/latest")
    public ApiResponse<VideoRespVO> getLatestByFaceId(
            @RequestParam("faceId") Long faceId,
            @RequestParam(value = "templateId", required = false) Long templateId) {
        try {
            log.debug("查询最新视频记录: faceId={}, templateId={}", faceId, templateId);

            VideoRespVO video = videoRepository.queryLatestByFaceIdAndTemplateId(faceId, templateId);

            if (video == null) {
                log.info("未找到视频记录: faceId={}, templateId={}", faceId, templateId);
                return ApiResponse.fail("未找到视频记录");
            }

            return ApiResponse.success(video);

        } catch (Exception e) {
            log.error("查询最新视频记录失败: faceId={}, templateId={}", faceId, templateId, e);
            return ApiResponse.fail("查询失败，请稍后重试");
        }
    }
}
