<?php

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Models\MarkdownFile;
use App\Models\MarkdownFileVO;
use App\Utils\Response as ApiResponse;

class MarkdownController
{
    public function getById(Request $request, Response $response, $args)
    {
        $id = $args['id'];
        $model = new MarkdownFile();
        $file = $model->findById($id);

        if (!$file) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('文件不存在')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(404);
        }

        // 检查是否为私密笔记
        if ($file['is_private'] == 1) {
            // 检查是否已认证
            $userId = $request->getAttribute('userId');
            if (!$userId) {
                // 未认证，返回空内容
                $response->getBody()->write(ApiResponse::json(ApiResponse::success('')));
                return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
            }
        }

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($file['content'])));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function getAll(Request $request, Response $response)
    {
        $model = new MarkdownFile();
        $files = $model->getAll();

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($files)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function update(Request $request, Response $response)
    {
        $data = $request->getParsedBody();
        $id = $data['id'] ?? null;

        if (!$id) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('缺少文件ID')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        $model = new MarkdownFile();
        $model->update($id, $data);

        $file = $model->findById($id);
        $response->getBody()->write(ApiResponse::json(ApiResponse::success($file)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function delete(Request $request, Response $response, $args)
    {
        $id = $args['id'];
        $userId = $request->getAttribute('userId');

        $model = new MarkdownFile();
        $model->softDelete($id, $userId);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success(null, '删除成功')));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function getByGroupingId(Request $request, Response $response, $args)
    {
        $groupingId = $args['groupingId'];
        $model = new MarkdownFile();
        $files = $model->getByGroupingId($groupingId);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($files)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function search(Request $request, Response $response)
    {
        $params = $request->getQueryParams();
        $keyword = $params['keyword'] ?? '';

        $model = new MarkdownFile();
        $files = $model->searchByTitle($keyword);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($files)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function getRecent(Request $request, Response $response)
    {
        // 使用 MarkdownFileVO 获取包含分组名称的数据
        $voModel = new MarkdownFileVO();
        $files = $voModel->getRecentWithGrouping(12);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($files)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    public function updateTitle(Request $request, Response $response, $args)
    {
        $id = $args['id'];
        $data = $request->getParsedBody();
        $title = $data['title'] ?? '';

        if (empty($title)) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('标题不能为空')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        $model = new MarkdownFile();
        $model->updateTitle($id, $title);
        $file = $model->findById($id);

        if (!$file) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('文件未找到或更新失败')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(404);
        }

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($file)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }
}
