<?php

namespace App\Imports;

use App\Models\Artist;
use App\Enums\ArtistCategory;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

class ArtistDataImport implements ToModel, WithHeadingRow
{
    public int $successCount = 0;
    public int $failCount = 0;

    public function __construct()
    {
        // 關閉 heading row 格式化
        HeadingRowFormatter::default('none');
    }

    public function model(array $row)
    {
        $name = trim($row['名稱'] ?? '');
        $category = trim($row['類別'] ?? '未定義');
        if (empty($name)) {
            $this->failCount++;
            return null;
        }

        try {
            Artist::firstOrCreate(
                ['name' => $name],
                ['category' => ArtistCategory::tryFrom($category) ?? ArtistCategory::Unset]
            );
            $this->successCount++;
        } catch (\Throwable $e) {
            $this->failCount++;
        }

        return null;
    }
    public function headingRow(): int
    {
        return 1;
    }
}