<?php

namespace Database\Seeders;

use App\Models\ImportTemplate;
use App\Models\ImportTemplateMapping;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class PaymentsImportTemplateSeeder extends Seeder
{
    public function run(): void
    {
        $template = ImportTemplate::query()->firstOrCreate([
            'name' => 'Payments CSV (reference)',
        ], [
            'uuid' => (string) Str::uuid(),
            'description' => 'Payments import by contract reference: contract.reference lookup + payment fields',
            'source_type' => 'csv',
            'default_record_type' => 'payments',
            'sample_headers' => [
                'Pogodba sklic',
                'Številka plačila',
                'Datum',
                'Znesek',
                'Sklic plačila',
            ],
            'is_active' => true,
            'meta' => [
                'delimiter' => ',',
                'enclosure' => '"',
                'escape' => '\\',
                'payments_import' => true,
                'contract_key_mode' => 'reference',
            ],
        ]);

        $mappings = [
            [
                'entity' => 'contracts',
                'source_column' => 'Pogodba sklic',
                'target_field' => 'contract.reference',
                'transform' => 'trim',
                'position' => 1,
            ],
            [
                'entity' => 'payments',
                'source_column' => 'Številka plačila',
                'target_field' => 'payment.payment_nu',
                'transform' => 'trim',
                'position' => 2,
            ],
            [
                'entity' => 'payments',
                'source_column' => 'Datum',
                'target_field' => 'payment.payment_date',
                'transform' => null,
                'position' => 3,
            ],
            [
                'entity' => 'payments',
                'source_column' => 'Znesek',
                'target_field' => 'payment.amount',
                'transform' => 'decimal',
                'position' => 4,
            ],
            [
                'entity' => 'payments',
                'source_column' => 'Sklic plačila',
                'target_field' => 'payment.reference',
                'transform' => 'trim',
                'position' => 5,
            ],
        ];

        foreach ($mappings as $map) {
            ImportTemplateMapping::firstOrCreate([
                'import_template_id' => $template->id,
                'source_column' => $map['source_column'],
            ], [
                'entity' => $map['entity'],
                'target_field' => $map['target_field'],
                'transform' => $map['transform'],
                'position' => $map['position'],
            ]);
        }
    }
}
