<?php

namespace App\Jobs;

use App\Models\Song;
use App\Models\Artist;
use App\Models\User;
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 ExportSqliteUserJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 600; // 可依資料量調整 timeout 秒數
    protected ?int $branchId;
    public bool $isSend;
    public function __construct(bool $isSend = true,?int $branchId = null){
        $this->isSend =$isSend ;
        $this->branchId = $branchId;
    }

    public function handle()
    {
        if($this->isSend){
            $sqlitePath = storage_path('app/database/tempUser.sqlite');
        }else{
            $sqlitePath = 'database/tempUser.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([
            // --- users ---
            'users' => [
                'modelClass' => User::class,
                'tableSchema' => function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('name');
                    $table->string('email')->unique();
                    $table->string('phone', 10)->unique();
                    $table->date('birthday')->nullable();        // 生日
                    $table->string('gender')->default('unset');  // 性別
                    $table->tinyInteger('status')->default(0);   // 啟動
                    $table->timestamp('email_verified_at')->nullable();
                    $table->rememberToken();
                    $table->text('api_plain_token')->nullable();
                    $table->timestamps();
                },
                'transformer' => fn (User $user) => [
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone,
                    'birthday' => $user->birthday,
                    'gender' => $user->gender?->value ?? 'unset',
                    'status' => $user->status,
                    'email_verified_at' => $user->email_verified_at,
                    'remember_token' => $user->remember_token,
                    'api_plain_token' => $user->api_plain_token,
                    'created_at' => $user->created_at,
                    'updated_at' => $user->updated_at,
                ],
            ],
            
            // --- roles ---
            'roles' => [
                'query' => fn () => DB::table('roles'),
                'tableSchema' => function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('name');
                    $table->string('guard_name');
                    $table->timestamps();
                },
                'transformer' => fn ($row) => [
                    'id' => $row->id,
                    'name' => $row->name,
                    'guard_name' => $row->guard_name,
                    'created_at' => $row->created_at,
                    'updated_at' => $row->updated_at,
                ],
            ],

            // --- permissions ---
            'permissions' => [
                'query' => fn () => DB::table('permissions'),
                'tableSchema' => function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('name');
                    $table->string('guard_name');
                    $table->timestamps();
                },
                'transformer' => fn ($row) => [
                    'id' => $row->id,
                    'name' => $row->name,
                    'guard_name' => $row->guard_name,
                    'created_at' => $row->created_at,
                    'updated_at' => $row->updated_at,
                ],
            ],

            // --- role_has_permissions ---
            'role_has_permissions' => [
                'query' => fn () => DB::table('role_has_permissions'),
                'tableSchema' => function (Blueprint $table) {
                    $table->unsignedBigInteger('permission_id');
                    $table->unsignedBigInteger('role_id');
                    $table->primary(['permission_id', 'role_id']);
                },
                'transformer' => fn ($row) => [
                    'permission_id' => $row->permission_id,
                    'role_id' => $row->role_id,
                ],
            ],

            // --- model_has_roles ---
            'model_has_roles' => [
                'query' => fn () => DB::table('model_has_roles'),
                'tableSchema' => function (Blueprint $table) {
                    $table->unsignedBigInteger('role_id');
                    $table->string('model_type');
                    $table->unsignedBigInteger('model_id');
                    $table->primary(['role_id', 'model_id', 'model_type'], 'model_has_roles_primary');
                },
                'transformer' => fn ($row) => [
                    'role_id' => $row->role_id,
                    'model_type' => $row->model_type,
                    'model_id' => $row->model_id,
                ],
            ],

            // --- model_has_permissions ---
            'model_has_permissions' => [
                'query' => fn () => DB::table('model_has_permissions'),
                'tableSchema' => function (Blueprint $table) {
                    $table->unsignedBigInteger('permission_id');
                    $table->string('model_type');
                    $table->unsignedBigInteger('model_id');
                    $table->index(['model_id', 'model_type']);
                    $table->primary(['permission_id', 'model_id', 'model_type']);
                },
                'transformer' => fn ($row) => [
                    'permission_id' => $row->permission_id,
                    'model_type' => $row->model_type,
                    'model_id' => $row->model_id,
                ],
            ],
        ]);
        if($this->isSend)
            SendSqliteFileJob::dispatch($sqlitePath, $this->branchId);

    }
}
