<?php

namespace App\Filament\Resources\Manage\Cooperations\Pages;

use App\Filament\Actions\BackAction;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Filament\Support\CheerfulNotification;
use App\Models\Cooperation;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Storage;

class EditCooperation extends EditRecord
{
    protected static string $resource = CooperationResource::class;

    public function mount(int|string $record): void
    {
        parent::mount($record);

        $media = Cooperation::find($record)
            ->getMedia('cooperations')
            ->where('custom_properties.doc_type', 'proposal-template')
            ->sortByDesc('created_at')
            ->first();

        if (! $media) {
            return;
        }

        $this->data['proposal_template'] = [
            $media->uuid => $media->getPathRelativeToRoot(),
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            BackAction::make()
                ->url(ListCooperations::getUrl()),
        ];
    }

    protected function getSavedNotification(): ?Notification
    {
        return CheerfulNotification::update();
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function afterSave(): void
    {
        $record = $this->getRecord();
        $data = $this->data;

        if (empty($data['proposal_template'])) {
            return;
        }

        $filePath = collect($data['proposal_template'])->first();

        $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

        if (! file_exists($fullPath)) {
            return;
        }

        $record
            ->addMediaFromDisk($filePath, config('filesystems.default'))
            ->preservingOriginal()
            ->withCustomProperties([
                'feature' => 'cooperations',
                'doc_type' => 'proposal-template',
                'date' => now()->toDateString(),
            ])
            ->toMediaCollection('cooperations');
    }
}
