-- SPDX-License-Identifier: Apache-2.0
-- SPDX-License-Identifier: Unlicense

FOR $contract IN (select * from active_vm fetch out) {
    LET $operator = (select * from $contract.out.operator)[0];
    LET $node_is_online = $contract.out.connected_at > $contract.out.disconnected_at;
    LET $price_per_minute = fn::vm_price_per_minute($contract.id);
    LET $amount_due = (time::now() - $contract.collected_at).mins() * $price_per_minute;
    LET $amount_paid = IF $amount_due > $contract.locked_nano {
        $contract.locked_nano
    } ELSE {
        $amount_due
    };
    IF $node_is_online {
        UPDATE $operator.id SET balance += $amount_paid;
        UPDATE $contract.id SET
            locked_nano -= $amount_paid,
            collected_at = time::now();
    } ELSE {
        LET $compensation = IF $amount_due > $operator.escrow {
            $operator.escrow
        } ELSE {
            $amount_due
        };
        UPDATE $operator.id SET escrow -= $compensation;
        UPDATE $contract.id SET
            locked_nano += $compensation,
            collected_at = time::now();
    };
    IF $amount_paid >= $contract.locked_nano {
        fn::delete_vm($contract.id);
    };
};

FOR $app_contract IN (select * from active_app fetch out) {
    LET $operator = (select * from $app_contract.out.operator)[0];
    LET $node_is_online = $app_contract.out.connected_at > $app_contract.out.disconnected_at;
    LET $price_per_minute = fn::app_price_per_minute($app_contract.id);
    LET $amount_due = (time::now() - $app_contract.collected_at).mins() * $price_per_minute;
    LET $amount_paid = IF $amount_due > $app_contract.locked_nano {
        $app_contract.locked_nano
    } ELSE {
        $amount_due
    };
    LET $escrow_multiplier = IF $operator.escrow < 5_000_000_000_000 { 1 } ELSE { 5 };
    IF $node_is_online {
        UPDATE $operator.id SET balance += $amount_paid * $escrow_multiplier;
        UPDATE $app_contract.id SET
            locked_nano -= $amount_paid,
            collected_at = time::now();
    } ELSE {
        LET $compensation = IF $amount_due > $operator.escrow {
            $operator.escrow
        } ELSE {
            $amount_due
        };
        UPDATE $operator.id SET escrow -= $compensation;
        UPDATE $app_contract.in SET balance += $compensation;
    };
    IF $amount_paid >= $app_contract.locked_nano {
        fn::delete_app($app_contract.id);
    }
}
