<?php

namespace App\Services\Import\Handlers;

use App\Models\Import;
use App\Models\Person\PersonAddress;
use App\Services\Import\BaseEntityHandler;

class AddressHandler extends BaseEntityHandler
{
    public function getEntityClass(): string
    {
        return PersonAddress::class;
    }

    /**
     * Override validate to skip validation if address is empty.
     * Handles both single values and arrays.
     */
    public function validate(array $mapped): array
    {
        $address = $mapped['address'] ?? null;
        
        // If array, check if all values are empty
        if (is_array($address)) {
            $hasValue = false;
            foreach ($address as $addr) {
                if (!empty($addr) && trim((string)$addr) !== '') {
                    $hasValue = true;
                    break;
                }
            }
            if (!$hasValue) {
                return ['valid' => true, 'errors' => []];
            }
            // Skip parent validation for arrays - we'll validate in process()
            return ['valid' => true, 'errors' => []];
        }
        
        // Single value - check if empty
        if (empty($address) || trim((string)$address) === '') {
            return ['valid' => true, 'errors' => []];
        }

        return parent::validate($mapped);
    }

    public function resolve(array $mapped, array $context = []): mixed
    {
        $address = $mapped['address'] ?? null;
        $personId = $mapped['person_id'] 
            ?? ($context['person']['entity']->id ?? null)
            ?? ($context['person']?->entity?->id ?? null);

        if (! $address || ! $personId) {
            return null;
        }

        // Find existing address by exact match for this person
        return PersonAddress::where('person_id', $personId)
            ->where('address', $address)
            ->first();
    }

    public function process(Import $import, array $mapped, array $raw, array $context = []): array
    {
        // Handle multiple addresses if address is an array
        $addresses = $mapped['address'] ?? null;
        
        // If single value, convert to array for uniform processing
        if (!is_array($addresses)) {
            $addresses = [$addresses];
        }
        
        $results = [];
        $insertedCount = 0;
        $skippedCount = 0;
        
        foreach ($addresses as $address) {
            // Skip if address is empty or blank
            if (empty($address) || trim((string)$address) === '') {
                $skippedCount++;
                continue;
            }
            
            // Resolve person_id from context
            $personId = $mapped['person_id'] ?? $context['person']['entity']?->id ?? null;

            if (! $personId) {
                $skippedCount++;
                continue;
            }

            $existing = $this->resolveAddress($address, $personId);

            // Check for duplicates if configured
            if ($this->getOption('deduplicate', true) && $existing) {
                $skippedCount++;
                continue;
            }

            // Create new address
            $payload = $this->buildPayloadForAddress($address);
            $payload['person_id'] = $personId;

            $addressEntity = new PersonAddress;
            $addressEntity->fill($payload);
            $addressEntity->save();
            
            $results[] = $addressEntity;
            $insertedCount++;
        }
        
        if ($insertedCount === 0 && $skippedCount > 0) {
            return [
                'action' => 'skipped',
                'message' => 'All addresses empty or duplicates',
            ];
        }
        
        return [
            'action' => 'inserted',
            'entity' => $results[0] ?? null,
            'entities' => $results,
            'applied_fields' => ['address', 'person_id'],
            'count' => $insertedCount,
        ];
    }
    
    protected function resolveAddress(string $address, int $personId): mixed
    {
        return PersonAddress::where('person_id', $personId)
            ->where('address', $address)
            ->first();
    }
    
    protected function buildPayloadForAddress(string $address): array
    {
        return [
            'address' => $address,
            'type_id' => 1, // Default to permanent address
        ];
    }
}
