<?php

namespace App\Jobs;

use App\Models\TextAd;
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 ExportSqliteTextAdJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 600;

    protected ?int $branchId;

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

    public function handle()
    {
        $sqlitePath = storage_path('app/database/tempTextAd.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([
            'text_ads' => [
                'query' => fn () => DB::table('text_ads'),
                'tableSchema' => function (Blueprint $table) {
                    $table->id();
                    $table->string('content')->comment('廣告內容');
                    $table->enum('color', ['black','white', 'red', 'green','blue'])->default('black')->comment('顯示顏色'); 
                    $table->integer('duration')->default(1)->comment('播放間隔時間（分鐘）');
                    $table->boolean('is_active')->default(true); // 啟用狀態
                    $table->timestamps();
                },
                'transformer' => fn ($row) => [
                    'content' => $row->content,
                    'color' => $row->color,
                    'duration' => $row->duration,
                    'is_active' => $row->is_active,
                    'created_at' => $row->created_at,
                    'updated_at' => $row->updated_at,
                ],
            ],
        ]);
        SendSqliteFileJob::dispatch($sqlitePath, $this->branchId);
    }
}
