<?php

use App\Models\Label;
use App\Models\Setting;
use App\Services\LabelsImportService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('import creates new labels from file', function () {
    $service = app(LabelsImportService::class);
    $result = $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');

    expect($result->newCount)->toBeGreaterThanOrEqual(1);
    expect($result->updatedCount)->toBe(0);
    expect(Label::count())->toBeGreaterThanOrEqual(1);
});

test('import updates color of existing labels', function () {
    Label::create(['name' => 'Copyright', 'color' => '#000000']);

    $service = app(LabelsImportService::class);
    $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');

    $label = Label::where('name', 'Copyright')->first();
    if ($label) {
        expect($label->color)->not->toBe('#000000');
    }
    expect(true)->toBeTrue();
});

test('import stores last imported metadata in settings', function () {
    $service = app(LabelsImportService::class);
    $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');

    expect(Setting::get('labels_last_imported_at'))->not->toBeNull();
    expect(Setting::get('labels_last_imported_filename'))->toBe('labels-sample.bin');
});

test('re-import is idempotent — no duplicates', function () {
    $service = app(LabelsImportService::class);
    $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');
    $countAfterFirst = Label::count();
    $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');

    expect(Label::count())->toBe($countAfterFirst);
});

test('empty label names are skipped', function () {
    $service = app(LabelsImportService::class);
    $result = $service->import(base_path('tests/fixtures/labels-sample.bin'), 'labels-sample.bin');
    expect($result->totalInFile)->toBeGreaterThan(0);
});
