<?php

namespace App\Services;

use App\Models\Label;
use App\Models\Setting;
use App\Services\DTO\LabelImportResult;
use Illuminate\Support\Facades\DB;
use ProPresenter\Parser\LabelsFileReader;

class LabelsImportService
{
    public function import(string $filePath, string $originalFilename): LabelImportResult
    {
        $library = LabelsFileReader::read($filePath);
        $newCount = 0;
        $updatedCount = 0;

        DB::transaction(function () use ($library, &$newCount, &$updatedCount): void {
            foreach ($library->getLabels() as $parserLabel) {
                $name = $parserLabel->getName();
                if ($name === '') {
                    continue;
                }
                $color = $parserLabel->getColorHex();
                $existing = Label::whereRaw('LOWER(name) = ?', [strtolower($name)])->first();
                if ($existing === null) {
                    Label::create([
                        'name' => $name,
                        'color' => $color,
                        'last_imported_at' => now(),
                    ]);
                    $newCount++;
                } else {
                    $existing->update([
                        'color' => $color,
                        'last_imported_at' => now(),
                    ]);
                    $updatedCount++;
                }
            }
        });

        Setting::set('labels_last_imported_at', now()->toIso8601String());
        Setting::set('labels_last_imported_filename', $originalFilename);

        return new LabelImportResult($newCount, $updatedCount, count($library->getLabels()));
    }
}
