<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Jobs\ExportSqliteUserJob;
use App\Jobs\ExportSqliteSongJob;
use App\Jobs\ExportSqliteFavoriteJob;
use Illuminate\Support\Facades\Bus;

class ExportSqlite extends Command
{
    /**
     * 指令名稱與參數定義
     *
     * @var string
     */
    protected $signature = 'export:sqlite 
                            {type : The type of data to export (song, user, all)} 
                            {--sync : Run the export job synchronously (without queue)}';

    /**
     * 指令描述
     *
     * @var string
     */
    protected $description = 'Export data from the database to SQLite (song, user, or both).';

    /**
     * 執行指令
     */
    public function handle()
    {
        $start = now();
        $type = strtolower($this->argument('type'));

        $this->info("[Export] 開始匯出資料類型: {$type}");

        try {
            if (!in_array($type, ['song', 'user', 'FavoriteSongs', 'all'])) {
                $this->error('[Export] 無效的 type，請使用：song、user 或 all');
                return 1;
            }

            $sync = $this->option('sync');

            if ($sync) {
                $this->warn('[Export] 使用同步模式執行...');

                if ($type === 'song' || $type === 'all') {
                    (new ExportSqliteSongJob())->handle();
                }
                if ($type === 'FavoriteSongs' || $type === 'all') {
                    (new ExportSqliteFavoriteJob())->handle();
                }
                if ($type === 'user' || $type === 'all') {
                    (new ExportSqliteUserJob())->handle();
                }

                $this->info('[Export] 匯出完成（同步）');
            } else {
                if ($type === 'all') {
                    // 確保 user -> song 順序
                    Bus::chain([
                        new ExportSqliteUserJob(),
                        new ExportSqliteFavoriteJob(),
                        new ExportSqliteSongJob(),
                    ])->dispatch();
                } elseif ($type === 'song') {
                } elseif ($type === 'FavoriteSongs') {
                    ExportSqliteSongJob::dispatch();
                } elseif ($type === 'user') {
                    ExportSqliteUserJob::dispatch();
                }

                $this->info('[Export] 匯出任務已派送至 queue');
            }

            $duration = now()->diffInSeconds($start);
            $this->info("[Export] 執行完成，用時 {$duration} 秒");

        } catch (\Throwable $e) {
            $this->error('[Export] 發生錯誤：' . $e->getMessage());
            return 1;
        }

        return 0;
    }
}