<?php

declare(strict_types=1);

namespace App\Models;

use App\Traits\MultiTenantScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PwaAuditLog extends Model
{
    use MultiTenantScope;

    protected $fillable = [
        'company_id',
        'user_id',
        'device_id',
        'device_name',
        'action',
        'resource_type',
        'resource_id',
        'channel',
        'offline_action',
        'offline_created_at',
        'idempotency_key',
        'ip_address',
        'user_agent',
        'request_data',
        'response_data',
        'metadata',
        'status',
        'error_message',
    ];

    protected $casts = [
        'offline_action' => 'boolean',
        'offline_created_at' => 'datetime',
        'request_data' => 'array',
        'response_data' => 'array',
        'metadata' => 'array',
    ];

    // Actions
    public const ACTION_LOGIN = 'login';

    public const ACTION_LOGOUT = 'logout';

    public const ACTION_PAYMENT_CREATED = 'payment_created';

    public const ACTION_PAYMENT_SYNCED = 'payment_synced';

    public const ACTION_SYNC_DATA = 'sync_data';

    public const ACTION_SYNC_PAYMENTS = 'sync_payments';

    public const ACTION_DEVICE_REGISTERED = 'device_registered';

    public const ACTION_DEVICE_REVOKED = 'device_revoked';

    public const ACTION_VIEW_CREDIT = 'view_credit';

    public const ACTION_VIEW_CLIENT = 'view_client';

    // Statuses
    public const STATUS_SUCCESS = 'success';

    public const STATUS_ERROR = 'error';

    public const STATUS_DUPLICATE = 'duplicate';

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope for filtering by action type.
     */
    public function scopeAction($query, string $action)
    {
        return $query->where('action', $action);
    }

    /**
     * Scope for filtering by date range.
     */
    public function scopeDateRange($query, string $from, string $to)
    {
        return $query->whereBetween('created_at', [$from, $to]);
    }

    /**
     * Scope for offline actions only.
     */
    public function scopeOffline($query)
    {
        return $query->where('offline_action', true);
    }

    /**
     * Scope for a specific device.
     */
    public function scopeDevice($query, string $deviceId)
    {
        return $query->where('device_id', $deviceId);
    }
}
