<?php

namespace App\Models\Audit;

use App\Models\Tenants\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AuditLog extends Model
{
    public $timestamps = false;

    protected $table = 'audit_logs';

    protected $fillable = [
        'tenant_id',
        'target_type',
        'target_id',
        'action',
        'before',
        'after',
        'actor_id',
        'ip',
        'ua',
        'created_at',
    ];

    protected $casts = [
        'before' => 'array',
        'after' => 'array',
        'created_at' => 'datetime',
    ];

    /**
     * 재고 관련 액션 목록
     */
    public const STOCK_ACTIONS = [
        'stock_increase' => '재고 증가',
        'stock_decrease' => '재고 차감',
        'stock_reserve' => '재고 예약',
        'stock_release' => '예약 해제',
    ];

    /**
     * 참조 타입 라벨
     */
    public const REFERENCE_TYPES = [
        'receiving' => '입고',
        'work_order' => '작업지시',
        'work_order_input' => '자재투입',
        'shipment' => '출하',
        'order' => '수주',
        'order_confirm' => '수주확정',
        'order_cancel' => '수주취소',
    ];

    /**
     * 테넌트
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 수행자
     */
    public function actor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'actor_id');
    }

    /**
     * 액션 라벨
     */
    public function getActionLabelAttribute(): string
    {
        return self::STOCK_ACTIONS[$this->action] ?? $this->action;
    }

    /**
     * 참조 타입 라벨
     */
    public function getReasonLabelAttribute(): ?string
    {
        $reason = $this->after['reason'] ?? null;

        return $reason ? (self::REFERENCE_TYPES[$reason] ?? $reason) : null;
    }

    /**
     * 수량 변화
     */
    public function getQtyChangeAttribute(): ?float
    {
        return $this->after['qty_change'] ?? null;
    }

    /**
     * LOT 번호
     */
    public function getLotNoAttribute(): ?string
    {
        return $this->after['lot_no'] ?? null;
    }

    /**
     * 참조 ID
     */
    public function getReferenceIdAttribute(): ?int
    {
        return $this->after['reference_id'] ?? null;
    }

    /**
     * 참조 타입
     */
    public function getReferenceTypeAttribute(): ?string
    {
        return $this->after['reference_type'] ?? null;
    }
}
