<?php

namespace App\Jobs;

use App\Models\Song;
use App\Models\SongLibraryCache;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;



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

    public function handle()
    {
        // 安全清空資料（兼容 SQLite 和其他資料庫）
        if (Schema::hasTable('song_library_cache')) {
            if (DB::getDriverName() === 'sqlite') {
                SongLibraryCache::query()->delete();
            } else {
                DB::table('song_library_cache')->truncate();
            }
        }

        $totalInserted = 0;

        Song::with(['artists', 'categories'])->chunk(500, function ($songs) use (&$totalInserted) {
            $rows = [];

            foreach ($songs as $song) {
                $sortedArtists = $song->artists->sortBy('id')->values();
                $artistA = $sortedArtists->get(0);
                $artistB = $sortedArtists->get(1);

                $rows[] = [
                    'song_id' => $song->id,
                    'song_name' => $song->name,
                    'song_simplified' => $song->simplified,
                    'phonetic_abbr' => $song->phonetic_abbr ?? '',
                    'pinyin_abbr' => $song->pinyin_abbr ?? '',
                    'strokes_abbr' => $song->strokes_abbr ?? 0,
                    'song_number' => $song->song_number ?? 0,
                    'artistA' => $artistA?->name,
                    'artistB' => $artistB?->name,
                    'artistA_simplified' => $artistA?->simplified,
                    'artistB_simplified' => $artistB?->simplified,
                    'artistA_category' => $artistA?->category?->value ?? '未定義',
                    'artistB_category' => $artistB?->category?->value ?? '未定義',
                    'artist_category' => in_array(\App\Enums\ArtistCategory::Group->value, [
                        $artistA?->category?->value,
                        $artistB?->category?->value,
                    ]) ? '團' : '未定義',
                    'song_filename' => $song->filename,
                    'song_category' => $song->categories->pluck('code')->unique()->sort()->implode(', '),
                    'language_name' => $song->language_type ?? '未定義',
                    'add_date' => $song->adddate,
                    'situation' => $song->situation?->value ?? '未定義',
                    'vocal' => $song->vocal,
                    'db_change' => $song->db_change,
                    'song_counts' => $song->song_counts ?? 0,
                    'updated_at' => now(),
                ];
            }

            collect($rows)->chunk(1000)->each(function ($chunk) use (&$totalInserted) {
                SongLibraryCache::insert($chunk->toArray());
                $totalInserted += $chunk->count();
            });
        });
        // 你也可以 log 或通知插入結果
        // logger("Exported {$totalInserted} songs to cache.");
    }
}
