<?php

namespace Database\Seeders;

use App\Models\ImportEntity;
use Illuminate\Database\Seeder;

class ImportEntitiesV2Seeder extends Seeder
{
    /**
     * Seed import_entities with v2 handler configurations.
     */
    public function run(): void
    {
        $entities = [
            [
                'key' => 'contracts',
                'canonical_root' => 'contract',
                'label' => 'Pogodbe',
                'fields' => ['reference', 'start_date', 'end_date', 'description', 'type_id', 'client_case_id', 'meta'],
                'field_aliases' => [],
                'aliases' => ['contract', 'contracts'],
                'supports_multiple' => false,
                'meta' => true,
                'rules' => [],
                'ui' => ['default_field' => 'reference', 'order' => 1],
                'handler_class' => \App\Services\Import\Handlers\ContractHandler::class,
                'validation_rules' => [
                    'reference' => 'required|string|max:255',
                ],
                'processing_options' => [
                    'update_mode' => 'update', // update, skip, error
                    'create_missing' => true,
                    'supports_reactivation' => true,
                    'merge_json_fields' => ['meta'],
                    'post_actions' => [
                        'attach_segment_id' => null,
                        'create_activity' => false,
                    ],
                ],
                'is_active' => true,
                'priority' => 100, // Highest - process first to establish chain
            ],
            [
                'key' => 'accounts',
                'canonical_root' => 'account',
                'label' => 'Računi',
                'fields' => ['reference', 'initial_amount', 'balance_amount', 'contract_id', 'contract_reference', 'type_id', 'active', 'description'],
                'field_aliases' => [],
                'aliases' => ['account', 'accounts'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [],
                'ui' => ['default_field' => 'reference', 'order' => 2],
                'handler_class' => \App\Services\Import\Handlers\AccountHandler::class,
                'validation_rules' => [
                    'reference' => 'required|string|max:255',
                    'contract_id' => 'required|integer|exists:contracts,id',
                ],
                'processing_options' => [
                    'update_mode' => 'update',
                    'require_contract' => true,
                    'track_balance_changes' => true,
                    'create_activity_on_balance_change' => true,
                    'history_import' => [
                        'skip_updates' => true,
                        'force_zero_balances' => true,
                        'auto_create_for_contract' => true,
                    ],
                ],
                'is_active' => true,
                'priority' => 50, // After Person and contacts
            ],
            [
                'key' => 'payments',
                'canonical_root' => 'payment',
                'label' => 'Plačila',
                'fields' => [
                    'reference',
                    'payment_nu',
                    'payment_date',
                    'amount',
                    'type_id',
                    'active',
                    // optional helpers for mapping by related records
                    'debt_id',
                    'account_id',
                    'account_reference',
                    'contract_reference'
                ],
                'field_aliases' => [
                    'datum' => 'payment_date',
                    'paid_at' => 'payment_date',
                    'number' => 'payment_nu',
                    'znesek' => 'amount',
                    'value' => 'amount'
                ],
                'aliases' => ['payment', 'payments'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [],
                'ui' => ['default_field' => 'reference', 'order' => 3],
                'handler_class' => \App\Services\Import\Handlers\PaymentHandler::class,
                'validation_rules' => [
                    'amount' => 'required|numeric',
                ],
                'processing_options' => [
                    'deduplicate_by' => ['account_id', 'reference'],
                    'create_booking' => true,
                    'create_activity' => false, // Based on PaymentSetting
                    'track_balance' => true,
                    'activity_note_template' => 'Prejeto plačilo [amount] [currency]',
                    'payments_import' => [
                        'require_fields' => ['contract.reference', 'payment.amount', 'payment.payment_date'],
                        'contract_key_mode' => 'reference',
                    ],
                ],
                'is_active' => true,
                'priority' => 40, // After Account
            ],
            [
                'key' => 'activities',
                'canonical_root' => 'activity',
                'label' => 'Aktivnosti',
                'fields' => ['client_case_id', 'contract_id', 'due_date', 'amount', 'note', 'action_id', 'decision_id'],
                'field_aliases' => [],
                'aliases' => ['activity', 'activities'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [],
                'ui' => ['default_field' => 'note', 'order' => 4],
                'handler_class' => \App\Services\Import\Handlers\ActivityHandler::class,
                'validation_rules' => [],
                'processing_options' => [
                    'require_contract' => false,
                    'require_client_case' => false,
                ],
                'is_active' => true,
                'priority' => 30, // After all primary entities
            ],
            [
                'key' => 'person',
                'canonical_root' => 'person',
                'label' => 'Osebe',
                'fields' => ['first_name', 'last_name', 'full_name', 'gender', 'birthday', 'tax_number', 'social_security_number', 'description'],
                'field_aliases' => [],
                'aliases' => ['person'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [],
                'ui' => ['default_field' => 'full_name', 'order' => 5],
                'handler_class' => \App\Services\Import\Handlers\PersonHandler::class,
                'validation_rules' => [],
                'processing_options' => [
                    'deduplicate_by' => ['tax_number', 'social_security_number'],
                    'update_mode' => 'update',
                ],
                'is_active' => true,
                'priority' => 90, // Third - derive from Contract/ClientCase chain if exists
            ],
            [
                'key' => 'emails',
                'canonical_root' => 'email',
                'label' => 'Email naslovi',
                'fields' => ['value', 'is_primary', 'label'],
                'field_aliases' => [],
                'aliases' => ['email', 'emails'],
                'supports_multiple' => true,
                'meta' => false,
                'rules' => [],
                'ui' => ['default_field' => 'value', 'order' => 6],
                'handler_class' => \App\Services\Import\Handlers\EmailHandler::class,
                'validation_rules' => [
                    'value' => 'required|email',
                ],
                'processing_options' => [
                    'deduplicate' => true,
                ],
                'is_active' => true,
                'priority' => 80, // After Person
            ],
            [
                'key' => 'person_addresses',
                'canonical_root' => 'address',
                'label' => 'Naslovi oseb',
                'fields' => ['address', 'city', 'postal_code', 'country', 'type_id', 'description'],
                'field_aliases' => [
                    'ulica' => 'address',
                    'naslov' => 'address',
                    'mesto' => 'city',
                    'posta' => 'postal_code',
                    'pošta' => 'postal_code',
                    'zip' => 'postal_code',
                    'drzava' => 'country',
                    'država' => 'country',
                    'opis' => 'description',
                ],
                'aliases' => ['person_addresses', 'address', 'addresses'],
                'supports_multiple' => true,
                'meta' => false,
                'rules' => [
                    ['pattern' => '/^(naslov|ulica|address)\b/i', 'field' => 'address'],
                    ['pattern' => '/^(mesto|city|kraj)\b/i', 'field' => 'city'],
                    ['pattern' => '/^(posta|pošta|zip|postal)\b/i', 'field' => 'postal_code'],
                    ['pattern' => '/^(drzava|država|country)\b/i', 'field' => 'country'],
                    ['pattern' => '/^(komentar|opis|opomba|comment|description|note)\b/i', 'field' => 'description'],
                ],
                'ui' => ['default_field' => 'address', 'order' => 7],
                'handler_class' => \App\Services\Import\Handlers\AddressHandler::class,
                'validation_rules' => [
                    'address' => 'required|string|max:255',
                ],
                'processing_options' => [
                    'deduplicate' => true,
                    'parent_entity' => 'person',
                ],
                'is_active' => true,
                'priority' => 70, // After Person
            ],
            [
                'key' => 'person_phones',
                'canonical_root' => 'phone',
                'label' => 'Telefoni oseb',
                'fields' => ['nu', 'country_code', 'type_id', 'description'],
                'field_aliases' => ['number' => 'nu'],
                'aliases' => ['phone', 'person_phones'],
                'supports_multiple' => true,
                'meta' => false,
                'rules' => [
                    ['pattern' => '/^(telefon|tel\.?|gsm|mobile|phone|kontakt)\b/i', 'field' => 'nu'],
                ],
                'ui' => ['default_field' => 'nu', 'order' => 8],
                'handler_class' => \App\Services\Import\Handlers\PhoneHandler::class,
                'validation_rules' => [
                    'nu' => 'required|string|max:50',
                ],
                'processing_options' => [
                    'deduplicate' => true,
                    'parent_entity' => 'person',
                ],
                'is_active' => true,
                'priority' => 60, // After Person
            ],
            [
                'key' => 'client_cases',
                'canonical_root' => 'client_case',
                'label' => 'Primeri',
                'fields' => ['client_ref'],
                'field_aliases' => [],
                'aliases' => ['client_case', 'client_cases', 'case', 'primeri', 'primer'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [
                    ['pattern' => '/^(client\s*ref|client_ref|case\s*ref|case_ref|primer|primeri|zadeva)\b/i', 'field' => 'client_ref'],
                ],
                'ui' => ['default_field' => 'client_ref', 'order' => 9],
                'handler_class' => \App\Services\Import\Handlers\ClientCaseHandler::class,
                'validation_rules' => [
                    'client_ref' => 'required|string|max:255',
                ],
                'processing_options' => [
                    'deduplicate_by' => ['client_ref'],
                    'update_mode' => 'update',
                ],
                'is_active' => true,
                'priority' => 95, // Second - process after Contract to establish chain
            ],
            [
                'key' => 'case_objects',
                'canonical_root' => 'case_object',
                'label' => 'Predmeti',
                'fields' => ['reference', 'name', 'description', 'type', 'contract_id'],
                'field_aliases' => [],
                'aliases' => ['case_object', 'case_objects', 'object', 'objects', 'predmet', 'predmeti'],
                'supports_multiple' => false,
                'meta' => false,
                'rules' => [
                    ['pattern' => '/^(sklic|reference|ref)\b/i', 'field' => 'reference'],
                    ['pattern' => '/^(ime|naziv|name|title)\b/i', 'field' => 'name'],
                    ['pattern' => '/^(tip|vrsta|type|kind)\b/i', 'field' => 'type'],
                    ['pattern' => '/^(komentar|opis|opomba|comment|description|note)\b/i', 'field' => 'description'],
                    ['pattern' => '/^(contract\s*id|contract_id|pogodba\s*id|pogodba_id)\b/i', 'field' => 'contract_id'],
                ],
                'ui' => ['default_field' => 'name', 'order' => 10],
                'handler_class' => \App\Services\Import\Handlers\CaseObjectHandler::class,
                'validation_rules' => [
                    'name' => 'required|string|max:255',
                ],
                'processing_options' => [
                    'require_contract' => false,
                ],
                'is_active' => true,
                'priority' => 10,
            ],
        ];

        foreach ($entities as $entity) {
            ImportEntity::updateOrCreate(
                ['key' => $entity['key']],
                $entity
            );
        }

        $this->command->info('Import entities v2 seeded successfully.');
    }
}
