<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\DberpPurchaseInquiryQuotes\Pages;

use App\Business\Purchase\Enums\PurchaseInquiryQuoteStatus;
use App\Business\Purchase\PurchaseInquiryQuoteService;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\DberpPurchaseInquiryQuoteResource;
use App\Models\DberpPurchaseInquiryQuote;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use App\Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;

class EditDberpPurchaseInquiryQuote extends EditRecord
{
    protected static string $resource = DberpPurchaseInquiryQuoteResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        /** @var DberpPurchaseInquiryQuote $record */
        return app(PurchaseInquiryQuoteService::class)->updateQuote($record, $data);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('mark_recommended')
                ->label(__('dberp.actions.mark_recommended'))
                ->requiresConfirmation()
                ->visible(fn (DberpPurchaseInquiryQuote $record): bool => $record->status === PurchaseInquiryQuoteStatus::Active->value && ! $record->is_recommended)
                ->action(function (): void {
                    app(PurchaseInquiryQuoteService::class)->markRecommended($this->record);
                    $this->record->refresh();
                }),
            Action::make('invalidate')
                ->label(__('dberp.actions.invalidate_quote'))
                ->requiresConfirmation()
                ->visible(fn (DberpPurchaseInquiryQuote $record): bool => $record->status !== PurchaseInquiryQuoteStatus::Invalidated->value)
                ->form([
                    Textarea::make('reason')
                        ->label(__('dberp.fields.invalidate_reason'))
                        ->rows(3),
                ])
                ->action(function (array $data): void {
                    app(PurchaseInquiryQuoteService::class)->invalidate($this->record, $data['reason'] ?? null);
                    $this->record->refresh();
                }),
        ];
    }
}