<?php

namespace App\Filament\Resources\PaperPartResource\Pages;

use App\Filament\Resources\PaperPartResource;
use App\Models\PaperQuestionRef;
use App\Models\PreQuestionCandidate;
use App\Services\QuestionExtractorService;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Facades\DB;

class ViewPaperPart extends ViewRecord
{
    protected static string $resource = PaperPartResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('rebuild_candidates')
                ->label('重新拆题')
                ->color('warning')
                ->requiresConfirmation()
                ->action(function (): void {
                    $part = $this->record;
                    $raw = trim((string) ($part->raw_markdown ?? ''));
                    if ($raw === '') {
                        Notification::make()
                            ->title('无法拆题')
                            ->body('该区块没有原始 Markdown 内容')
                            ->danger()
                            ->send();
                        return;
                    }

                    DB::transaction(function () use ($part): void {
                        PaperQuestionRef::where('part_id', $part->id)->delete();
                        PreQuestionCandidate::where('part_id', $part->id)->delete();

                        $sequence = 1;
                        app(QuestionExtractorService::class)->extractAndPersist($part, null, $sequence);
                    });

                    $part->refresh();

                    Notification::make()
                        ->title('拆题完成')
                        ->body('已根据最新规则重新生成题目候选')
                        ->success()
                        ->send();
                }),
        ];
    }
}
