<?php

namespace Kylin\LawCase\Services;

use Kylin\LawCase\Models\Client;
use Kylin\LawCase\Models\ConflictCheck;
use Kylin\LawCase\Enums\ConflictCheckStatus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ConflictCheckService
{
    /**
     * 执行利益冲突审查
     */
    public function check(int $clientId, string $opposingParty): ConflictCheck
    {
        $client = Client::findOrFail($clientId);

        $conflictingParties = [];
        $checkDetail = '';

        // 比对当事人名称
        $nameConflicts = Client::where('id', '!=', $clientId)
            ->where('client_name', $client->client_name)
            ->get();

        if ($nameConflicts->isNotEmpty()) {
            $conflictingParties = $nameConflicts->pluck('client_name')->toArray();
            $checkDetail .= "发现同名当事人：{$client->client_name}；";
        }

        // 比对对方当事人
        if ($opposingParty) {
            $opposingConflicts = Client::where('client_name', $opposingParty)
                ->whereHas('cases', function ($query) use ($clientId) {
                    $query->where('client_id', '!=', $clientId);
                })
                ->get();

            if ($opposingConflicts->isNotEmpty()) {
                foreach ($opposingConflicts as $conflict) {
                    $conflictingParties[] = $conflict->client_name;
                }
                $checkDetail .= "对方当事人存在利益冲突：{$opposingParty}；";
            }
        }

        $checkResult = empty($conflictingParties)
            ? ConflictCheckStatus::PASSED
            : ConflictCheckStatus::CONFLICT;

        $conflictCheck = ConflictCheck::create([
            'case_id' => null,
            'client_id' => $clientId,
            'check_result' => $checkResult,
            'check_detail' => $checkDetail ?: '未发现利益冲突',
            'conflicting_parties' => $conflictingParties,
            'checker_id' => auth()->id(),
            'checked_at' => now(),
        ]);

        $this->audit('conflict_check_performed', $conflictCheck, [
            'client_id' => $clientId,
            'opposing_party' => $opposingParty,
            'result' => $checkResult->value,
            'has_conflict' => ! empty($conflictingParties),
        ]);

        return $conflictCheck;
    }

    /**
     * 快速检索利益冲突
     */
    public function quickSearch(string $keyword): array
    {
        $clients = Client::where('client_name', 'like', "%{$keyword}%")
            ->orWhere('id_number', 'like', "%{$keyword}%")
            ->get();

        return $clients->map(function ($client) {
            return [
                'id' => $client->id,
                'client_name' => $client->client_name,
                'client_type' => $client->client_type,
                'cases_count' => $client->cases()->count(),
            ];
        })->toArray();
    }

    /**
     * 记录利益冲突审查审计日志
     *
     * 依据《律师法》第三十九条和律师执业利益冲突审查规则，
     * 利益冲突审查是律师执业的法定义务，审查结果需记录审计日志。
     */
    private function audit(string $event, ConflictCheck $check, array $extra = []): void
    {
        if (! class_exists(\Kylin\AuditLog\Models\AuditLog::class)) {
            return;
        }

        try {
            \Kylin\AuditLog\Models\AuditLog::create([
                'event' => $event,
                'model_type' => ConflictCheck::class,
                'model_id' => $check->id,
                'new_values' => $extra,
                'old_values' => null,
                'user_id' => auth()->id(),
                'ip' => request()?->ip(),
                'url' => request()?->fullUrl(),
                'tag' => 'law-case-conflict',
            ]);
        } catch (\Throwable $e) {
            Log::warning('利益冲突审查审计日志写入失败', [
                'error' => $e->getMessage(),
                'check_id' => $check->id,
                'event' => $event,
            ]);
        }
    }
}
