<?php

declare(strict_types=1);

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();
                }),
        ];
    }
}