<?php

namespace App\Jobs;

use App\Models\Artist;
use App\Enums\ArtistCategory;
use App\Helpers\ChineseNameConverter;
use App\Helpers\ChineseStrokesConverter;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class ImportArtistChunkJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Collection $rows;
    protected String $id;

    public function __construct(Collection $rows,String $id)
    {
        $this->rows = $rows;
        $this->id = $id;
    }

    public function handle(): void
    {
        Log::warning('匯入啟動', [
            'model' => "ImportArtistChunkJob",
            'rows_id' =>$this->id,
        ]);
        $now = now();
        foreach ($this->rows as $index => $row) {
            try {
                $name = $this->normalizeName($row['歌手姓名'] ?? '');

                if (empty($name) || Artist::where('name', $name)->exists()) {
                    continue;
                }

                // 字元處理
                $simplified = ChineseNameConverter::convertToSimplified($name);
                if (!$row->has('歌手注音')) {
                    $phoneticAbbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);
                } else {
                    $phoneticAbbr = trim($row['歌手注音'] ?? '');
                }
                $pinyinAbbr = ChineseNameConverter::getKTVPinyinAbbr($simplified);
                if (!$row->has('歌手筆畫')) {
                    $chars = preg_split('//u', $name, -1, PREG_SPLIT_NO_EMPTY);
                    $firstChar = $chars[0] ?? null;
                    $strokesAbbr = ( $firstChar && preg_match('/\p{Han}/u', $firstChar) ) ? ChineseStrokesConverter::getStrokes($firstChar) : 0;
                } else {
                    $strokesAbbr = trim($row['歌手筆畫'] ?? 0);
                } 

                // 準備 song 資料
                $toInsert[] = [
                    'name' => $name,
                    'category' => ArtistCategory::tryFrom(trim($row['歌手分類'] ?? '未定義')) ?? ArtistCategory::Unset,
                    'simplified' => $simplified,
                    'phonetic_abbr' => $phoneticAbbr,
                    'pinyin_abbr' => $pinyinAbbr,
                    'strokes_abbr' => $strokesAbbr,
                    'enable' =>trim($row['狀態'] ?? 1),
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
            } catch (\Throwable $e) {
                \Log::error("Row {$index} failed: {$e->getMessage()}", [
                    'row' => $row,
                    'trace' => $e->getTraceAsString()
                ]);
            }
        }
        Artist::insert($toInsert);
    }

    public function normalizeName(?string $str): string
    {
        return strtoupper(mb_convert_kana(trim($str ?? ''), 'as'));
    }
}