<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class IntegrationLog extends Model
{
    protected $fillable = [
        'uuid',
        'api_client_id',
        'integration_name',
        'system_name',
        'direction',
        'endpoint',
        'http_method',
        'record_type',
        'record_id',
        'record_uuid',
        'case_reference',
        'request_payload_hash',
        'request_payload_preview',
        'response_code',
        'response_body_preview',
        'status',
        'error_message',
        'retry_count',
        'last_attempt_at',
        'next_retry_at',
        'triggered_by',

        // Zero-trust API access audit fields
        'request_id',
        'route_name',
        'request_url',
        'request_query_preview',
        'request_headers_preview',
        'ip_address',
        'forwarded_for',
        'user_agent',
        'geo_country',
        'geo_city',
        'data_accessed',
        'data_scope',
        'allowed_district_ids',
        'partner_id',
        'duration_ms',
        'response_size_bytes',
        'response_record_count',
        'is_signed_request',
        'signature_status',
        'is_encrypted_payload',
        'rate_limit_per_minute',
        'rate_limit_remaining',
        'request_started_at',
        'request_completed_at',
    ];

    protected $casts = [
        'last_attempt_at' => 'datetime',
        'next_retry_at' => 'datetime',
        'request_started_at' => 'datetime',
        'request_completed_at' => 'datetime',
        'is_signed_request' => 'boolean',
        'is_encrypted_payload' => 'boolean',
        'duration_ms' => 'integer',
        'response_size_bytes' => 'integer',
        'response_record_count' => 'integer',
        'rate_limit_per_minute' => 'integer',
        'rate_limit_remaining' => 'integer',
    ];

    protected static function booted()
    {
        static::creating(function ($model) {
            if (empty($model->uuid)) {
                $model->uuid = (string) Str::uuid();
            }
        });
    }

    public function apiClient()
    {
        return $this->belongsTo(ApiClient::class, 'api_client_id');
    }
}
