<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Song;

class SongLibraryCache extends Model
{
    protected $table = 'song_library_cache';
    protected $primaryKey = 'song_id';
    public $incrementing = true;
    protected $keyType = 'int';
    const CREATED_AT = null;
    const UPDATED_AT = 'updated_at';

    // 可寫入的欄位（可依需要擴充）
    protected $fillable = [
        'song_id',
        'song_name',
        'song_simplified',
        'phonetic_abbr',
        'pinyin_abbr',
        'strokes_abbr',
        'song_number',
        'artistA',
        'artistB',
        'artistA_simplified',
        'artistB_simplified',
        'artistA_category',
        'artistB_category',
        'artist_category',
        'song_filename',
        'song_category',
        'language_name',
        'add_date',
        'situation',
        'vocal',
        'db_change',
        'song_counts',
        'updated_at',
    ];

    public static function syncFromSong(Song $song): void
    {
        $song->load(['artists', 'categories']);
        $sortedArtists = $song->artists->sortBy('id')->values();
        $artistA = $sortedArtists->get(0);
        $artistB = $sortedArtists->get(1);

        static::updateOrCreate(
            ['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(),
            ]
        );
    }
    
}
