const _MODULE = 'kapital_bank.kapital_bank.doctype.kapital_bank_api_test.kapital_bank_api_test';

frappe.ui.form.on('Kapital Bank API Test', {
	refresh(frm) {
		// ── Auth ────────────────────────────────────────────────────────────
		frm.add_custom_button(__('Login'),         () => _call(frm, 'do_login'),         __('Auth'));
		frm.add_custom_button(__('Logout'),        () => _call(frm, 'do_logout'),        __('Auth'));
		frm.add_custom_button(__('Refresh Token'), () => _call(frm, 'do_refresh_token'), __('Auth'));

		// ── Accounts ────────────────────────────────────────────────────────
		frm.add_custom_button(__('Get Accounts'),          () => _call(frm, 'do_get_accounts'),          __('Accounts'));
		frm.add_custom_button(__('Get Account Statement'), () => _call(frm, 'do_get_account_statement'), __('Accounts'));

		// ── Cards ───────────────────────────────────────────────────────────
		frm.add_custom_button(__('Get Cards'),          () => _call(frm, 'do_get_cards'),          __('Cards'));
		frm.add_custom_button(__('Get Card Statement'), () => _call(frm, 'do_get_card_statement'), __('Cards'));

		// ── Payments ────────────────────────────────────────────────────────
		frm.add_custom_button(__('Transfer Status'), () => _call(frm, 'do_transfer_status'), __('Payments'));
	}
});

function _call(frm, method) {
	const _execute = () => {
		frappe.show_progress(__('Running...'), 0, 100, __('Calling Kapital Bank API...'));
		frappe.call({
			method: `${_MODULE}.${method}`,
			args: { docname: frm.doc.name },
			freeze: false,
			callback(r) {
				frappe.hide_progress();
				if (r.exc) {
					frappe.msgprint({ title: __('Error'), message: r.exc, indicator: 'red' });
					return;
				}
				const res = r.message;
				frm.reload_doc();
				const ok = res && res.status === 'Success';
				frappe.show_alert({
					message: ok
						? __('Success ({0} ms)', [res.elapsed_ms])
						: __('Failed ({0} ms)', [res ? res.elapsed_ms : 0]),
					indicator: ok ? 'green' : 'red'
				}, 6);
			},
			error() {
				frappe.hide_progress();
				frappe.msgprint({ title: __('Error'), message: __('Request failed'), indicator: 'red' });
			}
		});
	};

	if (frm.is_new() || frm.is_dirty()) {
		frm.save('Save', _execute);
	} else {
		_execute();
	}
}
