<?php

namespace App\Observers;

use App\Models\ActivityLog;
use App\Models\MemberStatusLog;
use App\Models\User;
use App\Services\NotificationService;
use Illuminate\Support\Facades\Auth;

class UserObserver
{
    public function updated(User $user): void
    {
        // Pastikan role anggota selalu ada
        if (! $user->hasRole('anggota')) {
            $user->assignRole('anggota');
        }

        // Log perubahan status anggota
        if ($user->wasChanged('status')) {
            MemberStatusLog::create([
                'member_id'  => $user->id,
                'changed_by' => Auth::id() ?? $user->id,
                'old_status' => $user->getOriginal('status'),
                'new_status' => $user->status,
                'reason'     => $user->inactive_reason,
            ]);

            ActivityLog::create([
                'user_id'     => Auth::id(),
                'action'      => 'status_changed',
                'model_type'  => User::class,
                'model_id'    => $user->id,
                'description' => "Status anggota {$user->name} diubah dari {$user->getOriginal('status')} menjadi {$user->status}",
            ]);

            NotificationService::send(
                $user,
                'Status Keanggotaan Diubah',
                "Status Anda diubah menjadi {$user->status}" . ($user->inactive_reason ? ": {$user->inactive_reason}" : '.'),
                $user->status === 'aktif' ? 'success' : 'warning'
            );
        }
    }

    public function created(User $user): void
    {
        // Auto-assign role anggota jika belum punya role
        if ($user->roles->isEmpty()) {
            $user->assignRole('anggota');
        }

        ActivityLog::create([
            'user_id'     => Auth::id(),
            'action'      => 'created',
            'model_type'  => User::class,
            'model_id'    => $user->id,
            'description' => "Anggota baru {$user->name} ditambahkan",
        ]);
    }
}
