<?php

namespace App\Http\Controllers;

use App\Services\TextbookApiService;
use Filament\Notifications\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;

class TextbookController extends Controller
{
    protected TextbookApiService $apiService;

    public function __construct(TextbookApiService $apiService)
    {
        $this->apiService = $apiService;
    }

    /**
     * 删除教材 - 通过URL参数获取ID，完全绕过Filament的$record传递问题
     * 使用GET方法避免CSRF问题
     */
    public function delete(Request $request, int $id)
    {
        Log::info('TextbookController::delete called', [
            'textbook_id' => $id,
            'request_all' => $request->all()
        ]);

        if (!$id) {
            Notification::make()
                ->title('错误')
                ->body('无效的教材ID。')
                ->danger()
                ->send();

            return Redirect::route('filament.admin.resources.textbooks.index');
        }

        try {
            $deleted = $this->apiService->deleteTextbook($id);

            Log::info('Delete API result', [
                'deleted' => $deleted,
                'textbook_id' => $id
            ]);

            if ($deleted) {
                Notification::make()
                    ->title('成功')
                    ->body('教材删除成功。')
                    ->success()
                    ->send();
            } else {
                Notification::make()
                    ->title('错误')
                    ->body('删除失败，请重试。')
                    ->danger()
                    ->send();
            }
        } catch (\Exception $e) {
            Log::error('Delete error', [
                'error' => $e->getMessage(),
                'textbook_id' => $id
            ]);
            Notification::make()
                ->title('错误')
                ->body('删除失败：' . $e->getMessage())
                ->danger()
                ->send();
        }

        // 无论成功失败，都重定向回列表页面
        return Redirect::route('filament.admin.resources.textbooks.index');
    }
}
