<?php

namespace App\Services\Import\Handlers;

use App\Models\CaseObject;
use App\Models\Import;
use App\Services\Import\BaseEntityHandler;

class CaseObjectHandler extends BaseEntityHandler
{
    public function getEntityClass(): string
    {
        return CaseObject::class;
    }

    public function resolve(array $mapped, array $context = []): mixed
    {
        $reference = $mapped['reference'] ?? null;
        $name = $mapped['name'] ?? null;

        if (! $reference && ! $name) {
            return null;
        }

        // Try to find by reference first
        if ($reference) {
            $object = CaseObject::where('reference', $reference)->first();
            if ($object) {
                return $object;
            }
        }

        // Fall back to name if reference not found
        if ($name) {
            return CaseObject::where('name', $name)->first();
        }

        return null;
    }

    public function process(Import $import, array $mapped, array $raw, array $context = []): array
    {
        $existing = $this->resolve($mapped, $context);

        if ($existing) {
            // Update existing object
            $payload = $this->buildPayload($mapped, $existing);
            $appliedFields = $this->trackAppliedFields($existing, $payload);

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

            $existing->fill($payload);
            $existing->save();

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

        // Create new case object
        $payload = $this->buildPayload($mapped, new CaseObject);

        $caseObject = new CaseObject;
        $caseObject->fill($payload);
        $caseObject->save();

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

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

        $fields = ['reference', 'name', 'description', 'type', 'contract_id'];

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

        return $payload;
    }
}
