<?php

namespace App\Filament\Resources\TextbookResource\Pages;

use App\Filament\Resources\TextbookResource;
use App\Models\SourcePaper;
use App\Services\TextbookApiService;
use Filament\Resources\Pages\ViewRecord;

class ViewTextbook extends ViewRecord
{
    protected static string $resource = TextbookResource::class;

    protected string $view = 'filament.resources.textbook-resource.view';

    public array $catalogTree = [];

    public array $linkedPapers = [];

    public array $catalogCoverage = [];

    public int $unlinkedPaperCount = 0;

    public function mount(int|string $record): void
    {
        parent::mount($record);

        $apiService = app(TextbookApiService::class);
        $this->catalogTree = $apiService->getTextbookCatalog((int) $this->record->id, 'tree');

        $seriesName = $this->record->series->name ?? null;
        $this->linkedPapers = SourcePaper::query()
            ->when($seriesName, fn ($query) => $query->where('textbook_series', $seriesName))
            ->latest('updated_at')
            ->take(8)
            ->get()
            ->map(fn ($paper) => [
                'id' => $paper->id,
                'title' => $paper->title ?: $paper->full_title ?: '未命名卷子',
                'chapter' => $paper->chapter,
                'grade' => $paper->grade,
                'term' => $paper->term,
                'source_type' => $paper->source_type,
                'updated_at' => $paper->updated_at,
            ])
            ->toArray();

        $coverage = [];
        $unlinked = 0;
        SourcePaper::query()
            ->where('textbook_id', $this->record->id)
            ->get(['id', 'meta'])
            ->each(function ($paper) use (&$coverage, &$unlinked) {
                $catalogId = $paper->meta['catalog_node_id'] ?? null;
                if ($catalogId) {
                    $coverage[$catalogId] = ($coverage[$catalogId] ?? 0) + 1;
                } else {
                    $unlinked++;
                }
            });

        $this->catalogCoverage = $coverage;
        $this->unlinkedPaperCount = $unlinked;
    }
}
