<?php

namespace App\Services;

use App\Enums\ImportDatasourceStatus;
use App\Models\GlobalSetting;
use App\Models\ImportDatasource;
use App\Models\PbgTaskIndexIntegrations;
use App\Models\PbgTaskPrasarana;
use App\Models\PbgTaskRetributions;
use Exception;
use App\Models\PbgTask;
use App\Traits\GlobalApiResponse;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use App\Services\ServiceClient;

class ServiceSIMBG
{
    use GlobalApiResponse;
    private $email;
    private $password;
    private $simbg_host;
    private $fetch_per_page;
    private $service_client;
    /**
     * Create a new class instance.
     */
    public function __construct()
    {
        $this->email = trim((string) GlobalSetting::where('key','SIMBG_EMAIL')->first()->value);
        $this->password = trim((string) GlobalSetting::where('key','SIMBG_PASSWORD')->first()->value);
        $this->simbg_host = trim((string)GlobalSetting::where('key','SIMBG_HOST')->first()->value);
        $this->fetch_per_page = trim((string)GlobalSetting::where('key','FETCH_PER_PAGE')->first()->value);
        $this->service_client = new ServiceClient($this->simbg_host);
    }

    public function getToken(){
        $url = "/api/user/v1/auth/login/";
        $body = [
            'email' => $this->email,
            'password' => $this->password,
        ];
        
        $res = $this->service_client->post($url, $body);
        if(!$res->original['success']){
            Log::error("Token not retrieved ", ['response' => $res]);
            return null;
        }
        return $res;
    }

    public function syncIndexIntegration($uuid, $token)
    {
        $url = "/api/pbg/v1/detail/" . $uuid . "/retribution/indeks-terintegrasi/";

        $headers = [
            'Authorization' => "Bearer " . $token,
        ];
    
        $res = $this->service_client->get($url, $headers);

        Log::info("response index integration", ['res' => $res]);
    
        if (empty($res->original['success']) || !$res->original['success']) {
            // Log error
            Log::error("API response indicates failure", ['url' => $url, 'uuid' => $uuid]);
            return false;
        }
    
        $data = $res->original['data']['data'] ?? null;
        if (!$data) {
            Log::error("No valid data returned from API", ['url' => $url, 'uuid' => $uuid]);
            return false;
        }
    
        $resultData = PbgTaskIndexIntegrations::updateOrCreate(
            ['pbg_task_uid' => $uuid],
            [
                'indeks_fungsi_bangunan' => $data['indeks_fungsi_bangunan'] ?? null,
                'indeks_parameter_kompleksitas' => $data['indeks_parameter_kompleksitas'] ?? null,
                'indeks_parameter_permanensi' => $data['indeks_parameter_permanensi'] ?? null,
                'indeks_parameter_ketinggian' => $data['indeks_parameter_ketinggian'] ?? null,
                'faktor_kepemilikan' => $data['faktor_kepemilikan'] ?? null,
                'indeks_terintegrasi' => $data['indeks_terintegrasi'] ?? null,
                'total' => $data['total'] ?? null,
            ]
        );
    
        // Log success
        if ($resultData->wasRecentlyCreated) {
            Log::info("integration created successfully", ['uuid' => $uuid]);
        } else {
            Log::info("integration updated successfully", ['uuid' => $uuid]);
        }
        
        return true;
    }

    public function syncTaskList()
    {
        $initResToken = $this->getToken();

        $importDatasource = ImportDatasource::create([
            'status' => ImportDatasourceStatus::Processing->value,
        ]);

        if (empty($initResToken->original['data']['token']['access'])) {
            $importDatasource->update([
                'status' => ImportDatasourceStatus::Failed->value,
                'message' => 'Failed to retrieve token'
            ]);
            return $this->resError("Failed to retrieve token");
        }

        $apiToken = $initResToken->original['data']['token']['access'];
        $headers = ['Authorization' => "Bearer " . $apiToken];

        $url = "/api/pbg/v1/list/?page=1&size={$this->fetch_per_page}&sort=ASC";
        $initialResponse = $this->service_client->get($url, $headers);

        $totalPage = $initialResponse->original['data']['total_page'] ?? 0;
        if ($totalPage == 0) {
            $importDatasource->update([
                'status' => ImportDatasourceStatus::Failed->value,
                'message' => 'Invalid response: no total_page'
            ]);
            return $this->resError("Invalid response from API");
        }

        $savedCount = $failedCount = 0;

        for ($currentPage = 1; $currentPage <= $totalPage; $currentPage++) {
            $pageUrl = "/api/pbg/v1/list/?page={$currentPage}&size={$this->fetch_per_page}&sort=ASC";
            $getToken = $this->getToken();
            Log::info("response index integration", ['currentPage' => $currentPage]);
            if (empty($getToken->original['data']['token']['access'])) {
                $importDatasource->update([
                    'status' => ImportDatasourceStatus::Failed->value,
                    'message' => 'Failed to retrieve token'
                ]);
                break;
            }
            $token = $getToken->original['data']['token']['access'];
            $headers = ['Authorization' => "Bearer " . $token];
            $response = $this->service_client->get($pageUrl, $headers);
            $tasks = $response->original['data']['data'] ?? [];

            if (empty($tasks)) {
                $importDatasource->update([
                    'status' => ImportDatasourceStatus::Failed->value,
                    'message' => 'No data found on page'
                ]);
                Log::warning("No data found on page", ['page' => $currentPage]);
                break;
            }

            Log::info("executed page", ['page' => $currentPage, 'total' => $totalPage]);

            $tasksCollective = [];
            foreach ($tasks as $item) {
                try {
                    $tasksCollective[] = [
                        'uuid' => $item['uid'],
                        'name' => $item['name'],
                        'owner_name' => $item['owner_name'],
                        'application_type' => $item['application_type'],
                        'application_type_name' => $item['application_type_name'],
                        'condition' => $item['condition'],
                        'registration_number' => $item['registration_number'],
                        'document_number' => $item['document_number'],
                        'address' => $item['address'],
                        'status' => $item['status'],
                        'status_name' => $item['status_name'],
                        'slf_status' => $item['slf_status'] ?? null,
                        'slf_status_name' => $item['slf_status_name'] ?? null,
                        'function_type' => $item['function_type'],
                        'consultation_type' => $item['consultation_type'],
                        'due_date' => $item['due_date'],
                        'land_certificate_phase' => $item['land_certificate_phase'],
                        'task_created_at' => isset($item['created_at']) ? Carbon::parse($item['created_at'])->format('Y-m-d H:i:s') : null,
                        'updated_at' => now(),
                        'created_at' => now(),
                    ];

                    $this->syncIndexIntegration($item['uid'], $token);
                    $this->syncTaskDetailSubmit($item['uid'], $token);
                    $savedCount++;
                } catch (Exception $e) {
                    $failedCount++;
                    $importDatasource->update([
                        'status' => ImportDatasourceStatus::Failed->value,
                        'message' => "Successfully processed: $savedCount, Failed: $failedCount"
                    ]);
                    Log::error("Failed to process task", [
                        'error' => $e->getMessage(),
                        'task' => $item,
                    ]);
                    break;
                }
            }

            PbgTask::upsert($tasksCollective, ['uuid'], [
                'name', 'owner_name', 'application_type', 'application_type_name', 'condition',
                'registration_number', 'document_number', 'address', 'status', 'status_name',
                'slf_status', 'slf_status_name', 'function_type', 'consultation_type', 'due_date',
                'land_certificate_phase', 'task_created_at', 'updated_at'
            ]);
        }

        $importDatasource->update([
            'status' => ImportDatasourceStatus::Success->value,
            'message' => "Successfully processed: $savedCount, Failed: $failedCount"
        ]);

        Log::info("syncTaskList completed", ['savedCount' => $savedCount, 'failedCount' => $failedCount]);

        return $this->resSuccess(['savedCount' => $savedCount, 'failedCount' => $failedCount]);
    }


    public function syncTaskDetailSubmit($uuid, $token)
    {
        $url = "/api/pbg/v1/detail/" . $uuid . "/retribution/submit/";
        $headers = [
            'Authorization' => "Bearer " . $token,
        ];

        $res = $this->service_client->get($url, $headers);

        if (empty($res->original['success']) || !$res->original['success']) {
            // Log error
            Log::error("API response indicates failure", ['url' => $url, 'uuid' => $uuid]);
            return false;
        }

        $data = $res->original['data']['data'] ?? [];
        if (empty($data)) {
            Log::error("No data returned from API", ['url' => $url, 'uuid' => $uuid]);
            return false;
        }

        $detailCreatedAt = isset($data['created_at']) 
        ? Carbon::parse($data['created_at'])->format('Y-m-d H:i:s') 
        : null;

        $detailUpdatedAt = isset($data['updated_at']) 
        ? Carbon::parse($data['updated_at'])->format('Y-m-d H:i:s') 
        : null;

        $pbg_task_retributions = PbgTaskRetributions::updateOrCreate(
            ['detail_id' => $data['id']],
            [
                'detail_uid' => $data['uid'] ?? null,
                'detail_created_at' => $detailCreatedAt ?? null,
                'detail_updated_at' => $detailUpdatedAt ?? null,
                'luas_bangunan' => $data['luas_bangunan'] ?? null,
                'indeks_lokalitas' => $data['indeks_lokalitas'] ?? null,
                'wilayah_shst' => $data['wilayah_shst'] ?? null,
                'kegiatan_id' => $data['kegiatan']['id'] ?? null,
                'kegiatan_name' => $data['kegiatan']['name'] ?? null,
                'nilai_shst' => $data['nilai_shst'] ?? null,
                'indeks_terintegrasi' => $data['indeks_terintegrasi'] ?? null,
                'indeks_bg_terbangun' => $data['indeks_bg_terbangun'] ?? null,
                'nilai_retribusi_bangunan' => $data['nilai_retribusi_bangunan'] ?? null,
                'nilai_prasarana' => $data['nilai_prasarana'] ?? null,
                'created_by' => $data['created_by'] ?? null,
                'pbg_document' => $data['pbg_document'] ?? null,
                'underpayment' => $data['underpayment'] ?? null,
                'skrd_amount' => $data['skrd_amount'] ?? null,
                'pbg_task_uid' => $uuid,
            ]
        );

        $pbg_task_retribution_id = $pbg_task_retributions->id;

        $prasaranaData = $data['prasarana'] ?? [];
        if (!empty($prasaranaData)) {
            $insertData = array_map(fn($item) => [
                'pbg_task_uid' => $uuid,
                'pbg_task_retribution_id' => $pbg_task_retribution_id,
                'prasarana_id' => $item['id'] ?? null,
                'prasarana_type' => $item['prasarana_type'] ?? null,
                'building_type' => $item['building_type'] ?? null,
                'total' => $item['total'] ?? null,
                'quantity' => $item['quantity'] ?? null,
                'unit' => $item['unit'] ?? null,
                'index_prasarana' => $item['index_prasarana'] ?? null,
            ], $prasaranaData);
    
            // Use bulk insert or upsert for faster database operation
            PbgTaskPrasarana::upsert($insertData, ['prasarana_id']);
        }

        Log::info("retribution and prasarana successfully", ['uuid' => $uuid]);
        return true;
    }

}

