<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Models\Activity;

class ActivityLogger
{
    public static function log(string $description, ?Model $subject = null, array $properties = [], string $logName = 'default'): Activity
    {
        $activity = activity($logName)
            ->causedBy(Auth::user())
            ->withProperties($properties)
            ->log($description);

        if ($subject) {
            $activity->update(['subject_type' => get_class($subject), 'subject_id' => $subject->getKey()]);
        }

        return $activity;
    }

    public static function logLogin(string $email): void
    {
        self::log("User logged in with email: {$email}", null, [
            'email' => $email,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ], 'authentication');
    }

    public static function logLogout(): void
    {
        self::log('User logged out', null, [
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ], 'authentication');
    }

    public static function logView(Model $model, ?string $customDescription = null): void
    {
        $modelName = class_basename($model);
        $description = $customDescription ?: "Viewed {$modelName}";

        self::log($description, $model, [
            'action' => 'view',
            'url' => request()->fullUrl(),
            'method' => request()->method(),
        ], 'view');
    }

    public static function logCustomAction(string $action, string $description, ?Model $subject = null, array $properties = []): void
    {
        $properties = array_merge($properties, [
            'action' => $action,
            'url' => request()->fullUrl(),
            'method' => request()->method(),
            'ip_address' => request()->ip(),
        ]);

        self::log($description, $subject, $properties, 'custom');
    }

    public static function logSearch(string $query, string $module): void
    {
        self::log("Searched for '{$query}' in {$module}", null, [
            'search_query' => $query,
            'module' => $module,
            'results_count' => 0, // You can update this if needed
        ], 'search');
    }

    public static function logExport(string $type, ?string $filename = null): void
    {
        self::log("Exported {$type} data", null, [
            'export_type' => $type,
            'filename' => $filename,
            'format' => pathinfo($filename, PATHINFO_EXTENSION) ?? 'unknown',
        ], 'export');
    }

    public static function logError(string $error, ?Model $subject = null): void
    {
        self::log("Error occurred: {$error}", $subject, [
            'error_message' => $error,
            'url' => request()->fullUrl(),
            'method' => request()->method(),
        ], 'error');
    }
}
