<?php

namespace App\Jobs;

use App\Models\Branch;
use App\Models\Room;
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;

class ExportSqliteBranchJob 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/tempBranch.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([
            'branches' => [
                'modelClass' => Branch::class,
                'query' => fn () => Branch::where('id', $this->branchId)->get(),
                'tableSchema' => function ($table) {
                    $table->id();
                    $table->string('name')->comment('店名');
                    $table->string('external_ip')->comment('對外IP'); // 原本是 ipAddress，這裡改 string
                    $table->tinyInteger('enable')->default(1)->comment('狀態');
                    $table->timestamps();
                },
                'transformer' => fn ($branch) => [
                    'id' => $branch->id,
                    'name' => $branch->name,
                    'external_ip' => $branch->external_ip,
                    'enable' => $branch->enable ?? 1,
                    'created_at' => $branch->created_at,
                    'updated_at' => $branch->updated_at,
                ],
            ],
            'rooms' => [
                'modelClass' => Room::class,
                'query' => fn () => Room::where('branch_id', $this->branchId)->get(),
                'tableSchema' => function ($table) {
                    $table->id();
                    $table->unsignedBigInteger('branch_id')->comment('關聯分店');
                    $table->unsignedTinyInteger('floor')->default(1)->comment('樓層');
                    $table->string('type')->default('unset')->comment('包廂類別'); // enum 改成 string
                    $table->string('name')->comment('包廂名稱');
                    $table->string('internal_ip')->nullable()->comment('內部 IP');
                    $table->unsignedSmallInteger('port')->nullable()->comment('通訊 Port');
                    $table->tinyInteger('is_online')->default(0)->comment('連線狀態');
                    $table->string('status')->default('error')->comment('狀態'); // enum 改成 string
                    $table->dateTime('started_at')->nullable()->comment('開始時間');
                    $table->dateTime('ended_at')->nullable()->comment('結束時間');
                    $table->timestamps();
                },
                'transformer' => fn ($room) => [
                    'id' => $room->id,
                    'branch_id' => $room->branch_id,
                    'floor' => $room->floor,
                    'type' => $room->type,
                    'name' => $room->name,
                    'internal_ip' => $room->internal_ip,
                    'port' => $room->port,
                    'is_online' => $room->is_online,
                    'status' => $room->status,
                    'started_at' => $room->started_at,
                    'ended_at' => $room->ended_at,
                    'created_at' => $room->created_at,
                    'updated_at' => $room->updated_at,
                ],
            ]
        ]);
        SendSqliteFileJob::dispatch($sqlitePath, $this->branchId);
    }
}
