<?php

namespace App\Observers;

use App\Models\Activity;
use App\Models\ActivityLog;
use App\Services\NotificationService;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class ActivityObserver
{
    public function updated(Activity $activity): void
    {
        if ($activity->wasChanged('status')) {
            $old = $activity->getOriginal('status');
            $new = $activity->status;

            // Validasi workflow: draft→pending, pending→approved/rejected
            $allowed = [
                'draft'   => ['pending'],
                'pending' => ['approved', 'rejected'],
            ];

            if (isset($allowed[$old]) && ! in_array($new, $allowed[$old])) {
                Notification::make()->title('Transisi tidak diizinkan')
                    ->body("Status tidak bisa diubah dari {$old} ke {$new}.")
                    ->danger()->send();
                $activity->status = $old;
                return;
            }

            if ($new === 'approved' && $activity->wasChanged('executed_at') && empty($activity->execution_notes)) {
                Notification::make()->title('Catatan pelaksanaan wajib diisi')
                    ->danger()->send();
                $activity->executed_at = null;
                return;
            }

            ActivityLog::create([
                'user_id'     => Auth::id(),
                'action'      => 'status_changed',
                'model_type'  => Activity::class,
                'model_id'    => $activity->id,
                'description' => "Status kegiatan '{$activity->title}' diubah dari {$old} menjadi {$new}",
            ]);

            if ($new === 'pending') {
                NotificationService::toRole('ketua', 'Kegiatan Menunggu Persetujuan',
                    "Kegiatan \"{$activity->title}\" diajukan untuk disetujui.", 'warning',
                    route('filament.admin.resources.activities.edit', $activity));
            }

            if (in_array($new, ['approved', 'rejected']) && $activity->creator) {
                NotificationService::send(
                    $activity->creator,
                    $new === 'approved' ? 'Kegiatan Disetujui' : 'Kegiatan Ditolak',
                    "Kegiatan \"{$activity->title}\" telah " . ($new === 'approved' ? 'disetujui.' : 'ditolak.'),
                    $new === 'approved' ? 'success' : 'danger',
                    route('filament.admin.resources.activities.edit', $activity)
                );
            }
        }
    }

    public function created(Activity $activity): void
    {
        ActivityLog::create([
            'user_id'     => Auth::id(),
            'action'      => 'created',
            'model_type'  => Activity::class,
            'model_id'    => $activity->id,
            'description' => "Kegiatan baru dibuat: {$activity->title}",
        ]);
    }
}
