<?php

namespace App\Jobs;

use App\Services\SqliteExportService;
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;
use Illuminate\Database\Schema\Blueprint;


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

    public $timeout = 600; // 可依資料量調整 timeout 秒數

    protected ?int $branchId;

    public function __construct(?int $branchId = null)
    {
        $this->branchId = $branchId;
    }

    public function handle()
    {
        $sqlitePath = storage_path('app/database/tempFavorite.sqlite');

        // 確保資料夾存在
        if (!file_exists(dirname($sqlitePath))) {
            mkdir(dirname($sqlitePath), 0755, true);
        }

        // 如果檔案不存在就建立空檔案
        if (!file_exists($sqlitePath)) {
            file_put_contents($sqlitePath, '');
        }
        $connectionName = 'tempsqlite_' . md5($sqlitePath . microtime());
        config(["database.connections.{$connectionName}" => [
            'driver' => 'sqlite',
            'database' => $sqlitePath,
            'prefix' => '',
        ]]);

        $exporter = new SqliteExportService($connectionName);
        $exporter->exportMultiple([
            'FavoriteSongs' => [
                'query' => fn () => DB::table('FavoriteSongs'),
                'tableSchema' => function (Blueprint $table) {
                    $table->id();
                    $table->string('songNumber',20);
                    $table->string('userPhone', 10);
                    $table->timestamps();
                },
                'transformer' => fn ($row) => [
                    'songNumber' => $row->songNumber,
                    'userPhone' => $row->userPhone,
                    'created_at' => $row->created_at,
                    'updated_at' => $row->updated_at,
                ],
            ],
        ]);
        SendSqliteFileJob::dispatch($sqlitePath, $this->branchId);
    }
}
