<?php

namespace App\Services;

use App\Models\SystemLog;
use Illuminate\Support\Facades\Auth;

class SystemLogService
{
    /**
     * Log a system activity
     *
     * @param string $action
     * @param string $description
     * @param string|null $module
     * @param mixed|null $loggable
     * @return SystemLog
     */
    public static function log(string $action, string $description, ?string $module = null, $loggable = null): SystemLog
    {
        $data = [
            'user_id' => Auth::id(),
            'action' => $action,
            'description' => $description,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'module' => $module,
        ];

        // Add polymorphic relation if loggable is provided
        if ($loggable) {
            $data['loggable_id'] = $loggable->id;
            $data['loggable_type'] = get_class($loggable);
        }

        return SystemLog::create($data);
    }

    /**
     * Log user login
     */
    public static function logLogin($user): void
    {
        self::log('login', "User {$user->name} logged in successfully", 'auth', $user);
    }

    /**
     * Log user logout
     */
    public static function logLogout($user): void
    {
        self::log('logout', "User {$user->name} logged out", 'auth', $user);
    }

    /**
     * Log data creation
     */
    public static function logCreate($model, ?string $module = null): void
    {
        $modelName = class_basename($model);
        self::log('create', "Created {$modelName}: {$model->id}", $module, $model);
    }

    /**
     * Log data update
     */
    public static function logUpdate($model, ?string $module = null): void
    {
        $modelName = class_basename($model);
        self::log('update', "Updated {$modelName}: {$model->id}", $module, $model);
    }

    /**
     * Log data deletion
     */
    public static function logDelete($model, ?string $module = null): void
    {
        $modelName = class_basename($model);
        self::log('delete', "Deleted {$modelName}: {$model->id}", $module, $model);
    }

    /**
     * Log data export
     */
    public static function logExport(string $description, ?string $module = null): void
    {
        self::log('export', $description, $module);
    }

    /**
     * Log user management actions
     */
    public static function logUserManagement(string $action, string $description): void
    {
        self::log($action, $description, 'admin');
    }

    /**
     * Log security events
     */
    public static function logSecurity(string $action, string $description): void
    {
        self::log($action, $description, 'security');
    }
}
