"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _a, _ExchangeRateService_checkExchangeRateExist;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExchangeRateService = void 0;
const uuid_1 = require("uuid");
const database_1 = require("../application/database");
const response_error_1 = require("../error/response-error");
const exchange_rate_model_1 = require("../model/exchange-rate-model");
const exchange_rate_validation_1 = require("../validation/exchange-rate-validation");
const validation_1 = require("../validation/validation");
class ExchangeRateService {
    static create(request) {
        return __awaiter(this, void 0, void 0, function* () {
            // Validate the create request
            const createRequest = validation_1.Validation.validate(exchange_rate_validation_1.ExchangeRateValidation.CREATE, request);
            // Generate a UUID for the new exchange rate
            const exchangeRateId = (0, uuid_1.v4)();
            // Insert the new exchange rate into the database with the UUID
            yield database_1.db.query('INSERT INTO exchange_rate (id, currency, rate) VALUES (?, ?, ?)', [
                exchangeRateId,
                createRequest.currency,
                createRequest.rate_idr,
            ]);
            // Retrieve the newly created exchange rate by the UUID
            const exchangeRate = yield database_1.db.queryOne('SELECT * FROM exchange_rate WHERE id = ? LIMIT 1', [exchangeRateId]);
            if (!exchangeRate) {
                throw new response_error_1.ResponseError(500, 'Failed to create exchange rate');
            }
            return (0, exchange_rate_model_1.toExchangeRateResponse)(exchangeRate);
        });
    }
    static bulkUpdate(request) {
        return __awaiter(this, void 0, void 0, function* () {
            // Validate the bulk update request
            const bulkUpdateRequest = validation_1.Validation.validate(exchange_rate_validation_1.ExchangeRateValidation.BULK_UPDATE, request);
            // Start a transaction for batch processing
            yield database_1.db.transaction((conn) => __awaiter(this, void 0, void 0, function* () {
                for (const updateRequest of bulkUpdateRequest) {
                    const fieldsToUpdate = [];
                    const values = [];
                    // Add `currency` to the update if provided
                    if (updateRequest.currency !== undefined) {
                        fieldsToUpdate.push('currency = ?');
                        values.push(updateRequest.currency);
                    }
                    // Add `rate` to the update if provided
                    if (updateRequest.rate_idr !== undefined) {
                        fieldsToUpdate.push('rate_idr = ?');
                        values.push(updateRequest.rate_idr);
                    }
                    // Add the exchange rate ID to the values
                    values.push(updateRequest.id);
                    // Update the exchange rate in the database
                    yield conn.query(`UPDATE exchange_rate SET ${fieldsToUpdate.join(', ')} WHERE id = ?`, values);
                }
            }));
        });
    }
    static delete(id) {
        return __awaiter(this, void 0, void 0, function* () {
            // Check if the exchange rate exists
            yield __classPrivateFieldGet(this, _a, "m", _ExchangeRateService_checkExchangeRateExist).call(this, id);
            // Delete the exchange rate from the database
            yield database_1.db.query('DELETE FROM exchange_rate WHERE id = ?', [id]);
        });
    }
    static getAll() {
        return __awaiter(this, void 0, void 0, function* () {
            // Retrieve all exchange rates from the database
            const exchangeRates = yield database_1.db.query('SELECT * FROM exchange_rate ORDER BY created_at ASC');
            // Map each exchange rate to the response
            return exchangeRates.map(exchange_rate_model_1.toExchangeRateResponse);
        });
    }
    static get(id) {
        return __awaiter(this, void 0, void 0, function* () {
            // Retrieve a single exchange rate by ID
            const exchangeRate = yield database_1.db.queryOne('SELECT * FROM exchange_rate WHERE id = ? LIMIT 1', [id]);
            if (!exchangeRate) {
                throw new response_error_1.ResponseError(404, 'Exchange rate not found');
            }
            return (0, exchange_rate_model_1.toExchangeRateResponse)(exchangeRate);
        });
    }
}
exports.ExchangeRateService = ExchangeRateService;
_a = ExchangeRateService, _ExchangeRateService_checkExchangeRateExist = function _ExchangeRateService_checkExchangeRateExist(id) {
    return __awaiter(this, void 0, void 0, function* () {
        // Retrieve the exchange rate by ID
        const exchangeRate = yield database_1.db.queryOne('SELECT * FROM exchange_rate WHERE id = ? LIMIT 1', [id]);
        if (!exchangeRate) {
            throw new response_error_1.ResponseError(404, 'Exchange rate not found');
        }
    });
};
