<?php

namespace App\Models;

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

class ProjectAuditLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'project_id',
        'action',
        'entity_type',
        'entity_id',
        'description',
        'changes',
        'performed_by',
        'performed_at',
        'ip_address',
    ];

    protected $casts = [
        'performed_at' => 'datetime',
        'changes' => 'array',
    ];

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

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

    public static function log(
        Project $project,
        string $action,
        string $description,
        User $performedBy,
        ?string $entityType = null,
        ?int $entityId = null,
        ?array $changes = null
    ): void {
        static::create([
            'project_id' => $project->id,
            'action' => $action,
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'description' => $description,
            'changes' => $changes,
            'performed_by' => $performedBy->id,
            'performed_at' => now(),
            'ip_address' => request()->ip(),
        ]);
    }
}
