<?php

namespace App\Services;

use App\Models\Emotion;
use Illuminate\Support\Facades\DB;

class EmotionImportService
{
    public function import(string $filePath): array
    {
        $handle = fopen($filePath, 'r');
        if (! $handle) {
            return [0, 0];
        }

        $success = 0;
        $failed = 0;
        $headers = fgetcsv($handle, 0, ',');
        if (! $headers) {
            fclose($handle);
            return [0, 0];
        }

        $map = array_flip($headers);

        while (($row = fgetcsv($handle, 0, ',')) !== false) {
            try {
                DB::transaction(function () use ($row, $map, &$success) {
                    $nameDe = trim($row[$map['name_de']] ?? '');
                    $nameEn = trim($row[$map['name_en']] ?? '');

                    if ($nameDe === '' && $nameEn === '') {
                        throw new \RuntimeException('Name is required.');
                    }

                    $emotion = Emotion::create([
                        'name' => ['de' => $nameDe, 'en' => $nameEn],
                        'icon' => $row[$map['icon']] ?? null,
                        'color' => $row[$map['color']] ?? null,
                        'description' => [
                            'de' => $row[$map['description_de']] ?? null,
                            'en' => $row[$map['description_en']] ?? null,
                        ],
                        'sort_order' => (int) ($row[$map['sort_order']] ?? 0),
                        'is_active' => (int) ($row[$map['is_active']] ?? 1) ? 1 : 0,
                    ]);

                    $eventTypes = $row[$map['event_types']] ?? '';
                    if ($eventTypes) {
                        $slugs = array_filter(array_map('trim', explode('|', $eventTypes)));
                        if ($slugs) {
                            $ids = DB::table('event_types')->whereIn('slug', $slugs)->pluck('id')->all();
                            if ($ids) {
                                $emotion->eventTypes()->attach($ids);
                            }
                        }
                    }

                    $success++;
                });
            } catch (\Throwable $e) {
                $failed++;
            }
        }

        fclose($handle);

        return [$success, $failed];
    }
}
