<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ApiRequestLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'method',
        'endpoint',
        'status',
        'request_context',
        'response_summary',
        'response_body',
        'error_message',
        'duration_ms',
        'sync_log_id',
    ];

    protected function casts(): array
    {
        return [
            'request_context' => 'array',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    public function syncLog(): BelongsTo
    {
        return $this->belongsTo(CtsSyncLog::class, 'sync_log_id');
    }

    public function scopeByStatus(Builder $query, ?string $status): Builder
    {
        if ($status === null || $status === '') {
            return $query;
        }

        return $query->where('status', $status);
    }

    public function scopeSearch(Builder $query, ?string $search): Builder
    {
        if ($search === null || trim($search) === '') {
            return $query;
        }

        $term = '%'.trim($search).'%';

        return $query->where(function (Builder $builder) use ($term): void {
            $builder
                ->where('method', 'like', $term)
                ->orWhere('endpoint', 'like', $term)
                ->orWhere('error_message', 'like', $term);
        });
    }
}
