<?php

declare(strict_types=1);


namespace App\Blog\Controllers;

use App\Models\Category;
use App\Models\Comment;
use App\Models\Post;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\Tags\Tag;

/**
 * sablog 老 URL 兼容：全部 301 到新规范 URL，保证 SEO 不丢。
 */
class LegacyController extends Controller
{
    /**
     * 兼容首页查询串式：/?action=xxx
     */
    public function resolveAction(Request $request)
    {
        $action = $request->query('action');

        return match ($action) {
            'show' => $this->post($request->integer('id')),
            'category' => $this->category($request->integer('cid')),
            'index' => $request->filled('setdate') ? $this->month($request->query('setdate')) : redirect()->route('home'),
            'tags', 'tag', 'tagslist' => $this->tagList($request),
            'search' => redirect()->route('search', ['q' => $request->query('keyword', $request->query('q', ''))]),
            'links' => redirect()->route('links'),
            'archives' => redirect()->route('archives'),
            'comments' => redirect()->route('comments'),
            'login' => redirect()->route('login'),
            'reg' => redirect()->route('register'),
            'finduser' => $this->findUser($request->integer('uid')),
            default => abort(404),
        };
    }

    /**
     * /show-{id}-{page}.html
     */
    public function showRewritten(string $id)
    {
        return $this->post((int) $id);
    }

    /**
     * /category-{cid}-{page}.html
     */
    public function categoryRewritten(string $cid)
    {
        return $this->category((int) $cid);
    }

    /**
     * /archives-{date}-{page}.html
     */
    public function archivesRewritten(string $date)
    {
        return $this->month($date);
    }

    /**
     * /tag/{name}
     */
    public function tagByName(string $name)
    {
        $tag = Tag::findFromString($name, 'post');

        return $tag
            ? redirect()->route('tags.show', $tag->slug ?: $tag->name, 301)
            : abort(404);
    }

    /**
     * attachment.php?id=N -> 媒体地址
     */
    public function attachment(Request $request)
    {
        $id = $request->integer('id');
        $media = Media::query()
            ->where('collection_name', 'attachments')
            ->where('custom_properties->legacy_attachmentid', $id)
            ->first();

        if (! $media) {
            abort(404, '附件不存在');
        }

        if ($media->getCustomProperty('pending_sync')) {
            abort(404, '附件尚未同步到存储');
        }

        return redirect()->away($media->getUrl(), 301);
    }

    /**
     * post.php 表单兼容：登录 / 注册 / 登出 / 评论 / 搜索
     */
    public function postAction(Request $request)
    {
        return match ($request->input('action')) {
            'dologin' => app(AuthController::class)->login($request),
            'logout', 'clearcookies' => app(AuthController::class)->logout($request),
            'register' => app(AuthController::class)->register($request),
            'addcomment' => $this->addLegacyComment($request),
            'search' => redirect()->route('search', ['q' => $request->input('keyword', '')]),
            default => abort(404),
        };
    }

    private function addLegacyComment(Request $request)
    {
        $post = Post::find((int) $request->input('articleid', $request->input('id')));

        if (! $post || $post->status !== 'published') {
            return redirect()->route('home');
        }

        $data = $request->validate([
            'author' => ['nullable', 'string', 'max:50'],
            'email' => ['nullable', 'email', 'max:255'],
            'url' => ['nullable', 'url', 'max:255'],
            'content' => ['required', 'string'],
        ]);

        $status = (int) Setting::get('comment_audit', 0) === 1 ? 'pending' : 'published';

        $comment = $post->comments()->create([
            'user_id' => auth()->id(),
            'author_name' => $data['author'] ?? (auth()->user()->name ?? '匿名'),
            'author_email' => $data['email'] ?? null,
            'author_url' => $data['url'] ?? null,
            'content' => $data['content'],
            'ip' => $request->ip(),
            'status' => $status,
        ]);

        if ($status === 'published') {
            $post->increment('comment_count');
        }

        app(\App\Blog\Support\PluginManager::class)->doAction('comment.created', $comment);

        return redirect()->route('posts.show', $post->slug ?: $post->id)
            ->with($status === 'published' ? 'success' : 'error', $status === 'published' ? '评论已发布' : '评论已提交，等待审核')
            ->withFragment('comments');
    }

    private function post(int $id)
    {
        $post = Post::find($id);

        return $post
            ? redirect()->route('posts.show', $post->slug ?: $post->id, 301)
            : abort(404);
    }

    private function category(int $cid)
    {
        $category = Category::find($cid);

        return $category
            ? redirect()->route('category.show', $category->slug ?: $category->id, 301)
            : abort(404);
    }

    private function month(string $date)
    {
        if (! preg_match('/^(\d{4})(\d{2})?/', $date, $m)) {
            return redirect()->route('archives');
        }

        $year = $m[1];
        $month = $m[2] ?? null;

        return $month
            ? redirect()->route('archives.month', [$year, $month], 301)
            : redirect()->route('archives.month', [$year, '01'], 301);
    }

    private function tagList(Request $request)
    {
        if ($request->filled('id')) {
            // 老 sablog tagid 与新媒体 id 可能不一致，通过导入时记录的映射解析
            $legacyMap = json_decode((string) Setting::get('legacy_tags', '[]'), true) ?: [];
            $tagId = $legacyMap[(int) $request->query('id')] ?? null;
            $tag = $tagId ? Tag::find((int) $tagId) : Tag::find((int) $request->query('id'));

            return $tag
                ? redirect()->route('tags.show', $tag->slug ?: $tag->name, 301)
                : abort(404);
        }

        return redirect()->route('tags', [], 301);
    }

    private function findUser(int $uid)
    {
        if (auth()->check() && auth()->id() === $uid) {
            return redirect()->route('profile');
        }

        $user = User::find($uid);

        return $user
            ? redirect()->route('profile', [], 301)
            : abort(404);
    }
}
