<?php

namespace Lightscale\LaralightAuthLog;

use Lightscale\LaralightAuthLog\Models\AuthLog;
use Lightscale\LaralightAuthLog\Enums\Status;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Logout;
use Illuminate\Events\Dispatcher;

class AuthSubscriber
{

    private function handleEvent(Status $status, mixed $event, iterable $props): void
    {
        $log = new AuthLog([
            'status' => $status,
            'properties' => $props,
        ]);
        $log->user()->associate($event->user);
        $log->save();
    }

    public function handleLogin(Login $event): void
    {
        $this->handleEvent(Status::LoginSuccess, $event);
    }

    public function handleFailed(Failed $event): void
    {
        $creds = collect($event->credentials)->except('password');
        $this->handleEvent(Status::LoginFailure, $event, $creds);
    }

    public function handleLogout(Logout $event): void
    {
        $this->handleEvent(Status::Logout, $event);
    }

    public function subscribe(Dispatcher $events): array
    {
        return [
            Login::class => 'handleLogin',
            Failed::class => 'handleFailed',
            Logout::class => 'handleLogout',
        ];
    }
}