<?php

namespace App\Models\Backend;

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

class Transaction extends Model
{
    use HasFactory;

    protected $connection = 'backend';

    protected $table = 'transactions';

    public const UPDATED_AT = 'last_modified_at';

    public const STATUS_PENDING = 'pending';

    public const STATUS_PROCESSING = 'processing';

    public const STATUS_COMPLETED = 'completed';

    public const STATUS_FAILED = 'failed';

    protected $fillable = [
        'corporate_entity',
        'corporate_counterparty',
        'tx_date',
        'tx_amount',
        'tx_currency',
        'tx_purpose',
        'tx_country_outgoing',
        'tx_country_incoming',
        'source_file',
        'raw_payload',
        'status',
    ];

    protected $casts = [
        'tx_amount' => 'decimal:2',
    ];

    /**
     * KI-generierte Outputs für diese Transaktion
     */
    public function outputs(): HasMany
    {
        return $this->hasMany(TransactionOutput::class, 'transaction_id');
    }

    /**
     * Hole spezifischen Output-Typ
     */
    public function getOutput(string $key): ?array
    {
        return $this->outputs()
            ->where('output_key', $key)
            ->first()
            ?->content;
    }

    /**
     * Hole alle Outputs als Key-Value Array
     */
    public function getOutputsArray(): array
    {
        return $this->outputs()
            ->get()
            ->pluck('content', 'output_key')
            ->toArray();
    }

    /**
     * Company Info aus Outputs
     */
    public function getCompanyInfo(): ?array
    {
        return $this->getOutput('company_info');
    }

    /**
     * Risk Assessment aus Outputs
     */
    public function getRiskAssessment(): ?array
    {
        return $this->getOutput('risk_assessment');
    }

    /**
     * Sanctions Check aus Outputs
     */
    public function getSanctionsCheck(): ?array
    {
        return $this->getOutput('sanctions');
    }

    /**
     * PEP Check aus Outputs
     */
    public function getPepCheck(): ?array
    {
        return $this->getOutput('pep');
    }

    /**
     * Helper: Hat diese Transaction einen bestimmten Output?
     */
    public function hasOutput(string $key): bool
    {
        return $this->outputs()->where('output_key', $key)->exists();
    }

    /**
     * Ist KI-Verarbeitung abgeschlossen?
     */
    public function isProcessed(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    /**
     * Benötigt Review?
     */
    public function requiresReview(): bool
    {
        $risk = $this->getRiskAssessment();

        if (! $risk) {
            return true; // Keine Risk-Assessment → Review
        }

        return ($risk['score'] ?? 0) >= 70 || ($risk['requires_review'] ?? false);
    }

    /**
     * Get display-friendly company name
     */
    public function getCompanyName(): string
    {
        $companyInfo = $this->getCompanyInfo();

        return $companyInfo['name'] ?? $this->corporate_entity;
    }

    /**
     * Get risk score (0-100)
     */
    public function getRiskScore(): int
    {
        $risk = $this->getRiskAssessment();

        return $risk['score'] ?? 0;
    }

    /**
     * Get risk level (low, medium, high)
     */
    public function getRiskLevel(): string
    {
        $risk = $this->getRiskAssessment();

        return $risk['level'] ?? 'unknown';
    }
}
