<?php

namespace App\Services\Import\Handlers;

use App\Models\ClientCase;
use App\Models\Import;
use App\Services\Import\BaseEntityHandler;
use App\Services\Import\EntityResolutionService;
use Illuminate\Support\Facades\Log;

class ClientCaseHandler extends BaseEntityHandler
{
    protected EntityResolutionService $resolutionService;

    public function __construct($entityConfig = null)
    {
        parent::__construct($entityConfig);
        $this->resolutionService = new EntityResolutionService();
    }

    public function getEntityClass(): string
    {
        return ClientCase::class;
    }

    public function resolve(array $mapped, array $context = []): mixed
    {
        $clientRef = $mapped['client_ref'] ?? null;
        $clientId = $context['import']?->client_id ?? null;

        if (! $clientRef || ! $clientId) {
            return null;
        }

        // Find existing case by client_ref for this client
        return ClientCase::where('client_id', $clientId)
            ->where('client_ref', $clientRef)
            ->first();
    }

    public function process(Import $import, array $mapped, array $raw, array $context = []): array
    {
        $clientId = $import->client_id ?? null;
        
        if (! $clientId) {
            return [
                'action' => 'skipped',
                'message' => 'ClientCase requires client_id',
            ];
        }
        
        // PHASE 5: Use Person from context (already processed due to reversed priorities)
        // Priority order: explicit person_id > context person > resolved person
        $personId = $mapped['person_id'] ?? $context['person']['entity']?->id ?? null;
        
        // If no Person in context, try to resolve using EntityResolutionService
        if (!$personId) {
            $personId = $this->resolutionService->resolvePersonFromContext($import, $mapped, $context);
            
            if ($personId) {
                Log::info('ClientCaseHandler: Resolved Person via EntityResolutionService', [
                    'person_id' => $personId,
                ]);
            } else {
                Log::warning('ClientCaseHandler: No Person found in context or via resolution', [
                    'has_person_context' => isset($context['person']),
                    'has_mapped_person_id' => isset($mapped['person_id']),
                ]);
            }
        } else {
            Log::info('ClientCaseHandler: Using Person from context/mapping', [
                'person_id' => $personId,
                'source' => $mapped['person_id'] ? 'mapped' : 'context',
            ]);
        }

        $existing = $this->resolve($mapped, $context);

        if ($existing) {
            // Update if configured
            $mode = $this->getOption('update_mode', 'update');

            if ($mode === 'skip') {
                return [
                    'action' => 'skipped',
                    'entity' => $existing,
                    'message' => 'ClientCase already exists (skip mode)',
                ];
            }

            $payload = $this->buildPayload($mapped, $existing);
            
            // Update person_id if provided and different
            if ($personId && $existing->person_id !== $personId) {
                $payload['person_id'] = $personId;
            }

            $appliedFields = $this->trackAppliedFields($existing, $payload);

            if (empty($appliedFields)) {
                return [
                    'action' => 'skipped',
                    'entity' => $existing,
                    'message' => 'No changes detected',
                ];
            }

            $existing->fill($payload);
            $existing->save();
            
            Log::info('ClientCaseHandler: Updated existing ClientCase', [
                'client_case_id' => $existing->id,
                'person_id' => $existing->person_id,
                'applied_fields' => $appliedFields,
            ]);

            return [
                'action' => 'updated',
                'entity' => $existing,
                'applied_fields' => $appliedFields,
            ];
        }

        // Create new client case
        $payload = $this->buildPayload($mapped, new ClientCase);
        $payload['client_id'] = $clientId;

        if ($personId) {
            $payload['person_id'] = $personId;
        }

        $clientCase = new ClientCase;
        $clientCase->fill($payload);
        $clientCase->save();
        
        Log::info('ClientCaseHandler: Created new ClientCase', [
            'client_case_id' => $clientCase->id,
            'person_id' => $clientCase->person_id,
            'client_ref' => $clientCase->client_ref,
        ]);

        return [
            'action' => 'inserted',
            'entity' => $clientCase,
            'applied_fields' => array_keys($payload),
        ];
    }

    protected function buildPayload(array $mapped, $model): array
    {
        $payload = [];

        $fields = ['client_ref'];

        foreach ($fields as $field) {
            if (array_key_exists($field, $mapped)) {
                $payload[$field] = $mapped[$field];
            }
        }

        return $payload;
    }
}
