<?php

namespace App\Filament\Resources\Manage\Cooperations\Actions\Report;

use App\Enums\ApprovalStatus;
use App\Enums\CooperationStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Models\Report;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;

class AcceptAction extends Action
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Terima')
            ->icon(Heroicon::OutlinedCheck)
            ->color('success')
            ->action(function (Report $record): void {
                $record->update([
                    'status' => ApprovalStatus::ACCEPTED,
                ]);

                Notification::make()
                    ->title('Berhasil Diproses! ✨')
                    ->body("Laporan '{$record->title}' telah diterima. Notifikasi sudah dikirim ke media! 💪")
                    ->success()
                    ->send();

                $partnerUser = $record->mediaTaskAssignment?->partnerMedia?->company?->user;
                if ($partnerUser) {
                    $partnerUser->notify(new BroadcastNotification([
                        'title' => 'Mantap! Laporan Diterima 🎊✨',
                        'body' => "Hore! Laporan \"{$record->title}\" pada kerja sama \"{$record->mediaTaskAssignment->taskAssignment->cooperation->title}\" telah disetujui oleh Admin. Satu langkah lebih dekat! 🚀",
                        'action' => [
                            Action::make('view')
                                ->label('Lihat')
                                ->url(CooperationResource::getUrl('view', ['record' => $record->mediaTaskAssignment->taskAssignment->cooperation_id, 'relation' => 3])),
                        ],
                    ]));
                }
            })
            ->visible(
                fn (Report $record): bool => $record->mediaTaskAssignment?->taskAssignment?->cooperation?->status === CooperationStatus::VERIFICATION &&
                    ! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value) &&
                    $record->status === ApprovalStatus::PENDING
            );
    }
}
