#include "..\script_component.hpp"

/*
 * File: fnc_initGarageStore.sqf
 * Author: IDSolutions
 * Date: 2025-12-17
 * Last Update: 2026-01-30
 * Public: No
 *
 * Description:
 * Initializes the Garage store for managing player vehicles.
 * Provides methods for syncing, saving, and applying vehicles to the player's garage.
 *
 * Arguments:
 * None
 *
 * Return Value:
 * Garage store object [HASHMAP OBJECT]
 *
 * Example:
 * call forge_server_garage_fnc_initGarageStore
 */

#pragma hemtt ignore_variables ["_self"]
GVAR(GarageRepository) = compileFinal createHashMapFromArray [
    ["#base", EGVAR(common,BaseStore)],
    ["#type", "GarageRepository"],
    ["#create", {
        GVAR(GarageRegistry) = createHashMap;
        ["INFO", "Garage Repository Initialized!"] call EFUNC(common,log);
    }],
    ["get", {
        params [["_uid", "", [""]]];

        private _cached = GVAR(GarageRegistry) getOrDefault [_uid, nil];
        if !(isNil { _cached }) exitWith { _cached };

        ["garage:exists", [_uid]] call EFUNC(extension,extCall) params ["_result", "_isSuccess"];
        if !(_isSuccess) exitWith {
            ["ERROR", format ["Failed to check if garage %1 exists!", _uid]] call EFUNC(common,log);
            createHashMap
        };

        private _finalGarage = createHashMap;

        if (_result == "true") then {
            _finalGarage = _self call ["fetch", ["garage:get", _uid]];
            ["INFO", format ["Found garage for %1", _uid]] call EFUNC(common,log);
        } else {
            ["garage:create", [_uid]] call EFUNC(extension,extCall) params ["_result", "_isSuccess"];
            if !(_isSuccess) exitWith {
                ["ERROR", format ["Failed to create garage for %1!", _uid]] call EFUNC(common,log);
                createHashMap
            };

            ["INFO", format ["Created new garage for %1", _uid]] call EFUNC(common,log);
        };

        GVAR(GarageRegistry) set [_uid, _finalGarage];
        _finalGarage
    }]
];

GVAR(GarageStore) = createHashMapObject [[
    ["#base", GVAR(GarageRepository)],
    ["#type", "IGarageStore"],
    ["#create", {
        ["INFO", "Garage Store Initialized!"] call EFUNC(common,log);
    }],
    ["init", {
        params [["_uid", "", [""]]];

        private _garage = _self call ["get", [_uid]];
        private _player = [_uid] call EFUNC(common,getPlayer);

        [CRPC(garage,responseInitGarage), [_garage], _player] call CFUNC(targetEvent);
    }]
]];

GVAR(GarageStore)
