<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TenantUserMasterSyncService
{
    public function sync(User $tenantUser): ?int
    {
        $masterConfig = [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ];

        config(['database.connections.master_sync' => $masterConfig]);

        $authUser = Auth::user();

        $masterData = [
            'name' => $tenantUser->name,
            'email' => $tenantUser->email,
            'password' => $tenantUser->password,
            'tenant_database' => $authUser?->tenant_database,
            'tenant_username' => $authUser?->tenant_username,
            'tenant_password' => $authUser?->tenant_password,
            'tenant_host' => '127.0.0.1',
            'updated_at' => now(),
        ];

        $masterQuery = DB::connection('master_sync')->table('users');
        $masterUser = null;

        if (!empty($tenantUser->master_user_id)) {
            $masterUser = (clone $masterQuery)->where('id', $tenantUser->master_user_id)->first();
        }

        if (!$masterUser && !empty($tenantUser->email)) {
            $masterUser = (clone $masterQuery)->where('email', $tenantUser->email)->first();
        }

        if ($masterUser) {
            if (!empty($tenantUser->password)) {
                $masterData['password'] = $tenantUser->password;
            }

            (clone $masterQuery)->where('id', $masterUser->id)->update($masterData);

            if ((int) $tenantUser->master_user_id !== (int) $masterUser->id) {
                $tenantUser->forceFill([
                    'master_user_id' => $masterUser->id,
                ])->saveQuietly();
            }

            return (int) $masterUser->id;
        }

        $masterData['password'] = $tenantUser->password;
        $masterData['created_at'] = now();

        $masterId = (clone $masterQuery)->insertGetId($masterData);

        $tenantUser->forceFill([
            'master_user_id' => $masterId,
        ])->saveQuietly();

        return (int) $masterId;
    }

    public function delete(User $tenantUser): bool
    {
        $masterConfig = [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ];

        config(['database.connections.master_sync' => $masterConfig]);

        $query = DB::connection('master_sync')->table('users');

        if (!empty($tenantUser->master_user_id)) {
            return $query->where('id', $tenantUser->master_user_id)->delete() > 0;
        }

        if (!empty($tenantUser->email)) {
            return $query->where('email', $tenantUser->email)->delete() > 0;
        }

        return false;
    }
}
