// Copyright (c) Juspay Technologies. All rights reserved.
//
// Package: ucs.v2
// File: services.proto
//
// Overview:
//   This file exposes the gRPC service interfaces that serve as the primary entry
//   point for consuming the Unified Connector Service (UCS) API. You interact with
//   these services to process payments, manage refunds, handle disputes, and
//   authenticate payment methods across 50+ payment connectors.
//
//   You import payment.proto for all shared message types and enumerations.
//
// Handling Multi-Step Flows:
//   You can handle complex operations like 3DS and DDC through multiple RPCs to handle
//   external redirects and asynchronous device data collection. You pass the
//   ConnectorState from each response to the next request to maintain session
//   continuity across the entire workflow.
//
// Handling Webhook Flows:
//   Process inbound webhook notifications from connectors through EventService.HandleEvent.
//   Pass the raw HTTP request details to receive verified, unified typed responses that
//   reflect the latest payment states without polling connector APIs.
//
// Services:
//   ┌──────────────────────────────────────┬─────────────────────────────────────────────────────────────────────────────┐
//   │ Service                              │ Purpose                                                                     │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ PaymentService                       │ Process payments from authorization to settlement. Authorize funds, capture │
//   │                                      │ payments, issue refunds, and void transactions through a single interface.  │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ RecurringPaymentService              │ Charge and revoke recurring payments. Process subscription billing and      │
//   │                                      │ cancel mandates when customers end their recurring agreements.              │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ SurchargeService                     │ Calculate additional fees for payment processing based on payment method,   │
//   │                                      │ network, or regional regulations to ensure accurate cost recovery.          │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ RefundService                        │ Retrieve and synchronize refund statuses. Track refund progress across      │
//   │                                      │ payment processors to ensure accurate settlement of customer refunds.       │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ DisputeService                       │ Manage chargeback disputes. Submit evidence, defend claims, and accept      │
//   │                                      │ liability to protect revenue and maintain compliance with card networks.    │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ EventService                         │ Process asynchronous webhook events from payment processors. Receive        │
//   │                                      │ real-time updates about payment state changes without polling APIs.         │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ PaymentMethodService                 │ Tokenize and retrieve payment methods. Vault sensitive card data to enable  │
//   │                                      │ one-click payments and recurring billing without PCI exposure.              │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ CustomerService                      │ Create and manage customer profiles. Store payer information at the         │
//   │                                      │ connector to streamline future transactions and improve authorization rates.│
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ MerchantAuthenticationService        │ Generate access tokens and session credentials. Authenticate your           │
//   │                                      │ application and initialize SDK sessions for wallet payments like Apple Pay. │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ PaymentMethodAuthenticationService   │ Execute 3D Secure authentication flows. Verify cardholder identity through  │
//   │                                      │ frictionless or challenge-based checks to reduce fraud liability.           │
//   ├──────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────┤
//   │ FraudAndRiskManagementService        │ Evaluate fraud risk before and after payment processing. Analyze            │
//   │                                      │ transaction details to approve, reject, or flag payments for review.        │
//   └──────────────────────────────────────┴─────────────────────────────────────────────────────────────────────────────┘
//
//
// Related Files:
//   - payment.proto         — All shared message and enum definitions
//   - payment_methods.proto — Payment method data types

syntax = "proto3";

package types;

import "payment.proto";
import "payouts.proto";
import "surcharge.proto";
import "frm.proto";

option go_package = "github.com/juspay/connector-service/crates/types-traits/grpc-api-types/proto;proto";

// ============================================================================
// SERVICE DEFINITIONS
// ============================================================================

// ============================================================================
// EVENT SERVICE — Two-phase inbound webhook processing.
//   1. ParseEvent   — parse payload, return reference + event type (no credentials).
//   2. HandleEvent  — verify source, return unified typed response (PSync/RSync/Dispute shape).
// For single-call processing when secrets are known upfront, use CompositeEventService.
// ============================================================================

service EventService {
  // Parse a raw webhook payload without credentials.
  // Returns resource reference and event type — sufficient to resolve secrets or early-exit.
  rpc ParseEvent(EventServiceParseRequest) returns (EventServiceParseResponse);

  // Verify webhook source and return a unified typed response.
  // Response mirrors PaymentService.Get / RefundService.Get / DisputeService.Get.
  rpc HandleEvent(EventServiceHandleRequest) returns (EventServiceHandleResponse);

  // Notify connectors about events (payment succeeded, refund succeeded, refund failed).
  rpc NotifyConnector(NotifyConnectorRequest) returns (NotifyConnectorResponse);
}

// ============================================================================
// PAYMENT SERVICE — Core payment lifecycle operations spanning authorization,
//                    capture, void, refund, and order management.
// ============================================================================

// Unified service definition for all payment related operations.
service PaymentService {
  // Authorize a payment amount on a payment method. This reserves funds
  // without capturing them, essential for verifying availability before finalizing.
  rpc Authorize(PaymentServiceAuthorizeRequest) returns (PaymentServiceAuthorizeResponse);

  // Retrieve current payment status from the payment processor. Enables synchronization
  // between your system and payment processors for accurate state tracking.
  rpc Get(PaymentServiceGetRequest) returns (PaymentServiceGetResponse);

  // Cancel an authorized payment that has not been captured. Releases held funds
  // back to the customer's payment method when a transaction cannot be completed.
  rpc Void(PaymentServiceVoidRequest) returns (PaymentServiceVoidResponse);

  // Reverse a captured payment in full. Initiates a complete refund when you need
  // to cancel a settled transaction rather than just an authorization.
  rpc Reverse(PaymentServiceReverseRequest) returns (PaymentServiceReverseResponse);

  // Finalize an authorized payment by transferring funds. Captures the authorized
  // amount to complete the transaction and move funds to your merchant account.
  rpc Capture(PaymentServiceCaptureRequest) returns (PaymentServiceCaptureResponse);

  // Create a payment order for later processing. Establishes a transaction context
  // that can be authorized or captured in subsequent API calls.
  rpc CreateOrder(PaymentServiceCreateOrderRequest) returns (PaymentServiceCreateOrderResponse);

  // Process a partial or full refund for a captured payment. Returns funds to the
  // customer when goods are returned or services are cancelled.
  rpc Refund(PaymentServiceRefundRequest) returns (RefundResponse);

  // Increase the authorized amount for an existing payment. Enables you to capture
  // additional funds when the transaction amount changes after initial authorization.
  rpc IncrementalAuthorization(PaymentServiceIncrementalAuthorizationRequest) returns (PaymentServiceIncrementalAuthorizationResponse);

  // Verify and process redirect responses from 3D Secure or other external flows.
  // Validates authentication results and updates payment state accordingly.
  rpc VerifyRedirectResponse(PaymentServiceVerifyRedirectResponseRequest) returns (PaymentServiceVerifyRedirectResponseResponse);

  // Configure a payment method for recurring billing. Sets up the mandate and
  // payment details needed for future automated charges.
  rpc SetupRecurring(PaymentServiceSetupRecurringRequest) returns (PaymentServiceSetupRecurringResponse);

  // ============================================================================
  // TOKENIZED PAYMENT METHODS — For merchants holding connector-issued payment
  // method tokens (e.g., Stripe pm_xxx, Adyen stored ref, Braintree nonce).
  // ============================================================================
  // 3DS flows (PaymentMethodAuthenticationService) are NOT available here —
  // PSP tokens cannot be passed to an external 3DS directory server.
  // For 3DS on stored tokens, use connector_feature_data to trigger
  // connector-side delegated authentication (Stripe, Adyen, etc. support this).

  // Authorize using a connector-issued payment method token.
  rpc TokenAuthorize(PaymentServiceTokenAuthorizeRequest) returns (PaymentServiceAuthorizeResponse);

  // Setup a recurring mandate using a connector token.
  rpc TokenSetupRecurring(PaymentServiceTokenSetupRecurringRequest) returns (PaymentServiceSetupRecurringResponse);

  // ============================================================================
  // PROXIED PAYMENT METHODS — For merchants using VGS, Basis Theory, Spreedly,
  // or similar vault providers that proxy traffic and substitute aliases.
  // ============================================================================
  // VaultAliasCard fields contain vault alias tokens that the proxy substitutes
  // with real card data before forwarding to the connector.
  //
  // The proxy URL must be set in RequestConfig.http.proxy when constructing
  // the client, or set in the gRPC server's outbound HTTP configuration.
  //
  // 3DS flows (PreAuthenticate, Authenticate, PostAuthenticate) are available
  // because the vault proxy substitutes aliases with the real PAN before
  // forwarding to the 3DS server (Netcetera, JuspayThreeDsServer, etc.).

  // Authorize using vault-aliased card data. Proxy substitutes before connector.
  rpc ProxyAuthorize(PaymentServiceProxyAuthorizeRequest) returns (PaymentServiceAuthorizeResponse);

  // Setup recurring mandate using vault-aliased card data.
  rpc ProxySetupRecurring(PaymentServiceProxySetupRecurringRequest) returns (PaymentServiceSetupRecurringResponse);

}

// ======================================================================================
// RECURRING PAYMENT SERVICE — Manages recurring payment management operations including
//                              charging and revoking mandates.
// ======================================================================================

service RecurringPaymentService {
  // Charge using an existing stored recurring payment instruction. Processes repeat payments for
  // subscriptions or recurring billing without collecting payment details.
  rpc Charge(RecurringPaymentServiceChargeRequest) returns (RecurringPaymentServiceChargeResponse);

  // Cancel an existing recurring payment mandate. Stops future automatic
  // charges on customer's stored consent for subscription cancellations.
  rpc Revoke(RecurringPaymentServiceRevokeRequest) returns (RecurringPaymentServiceRevokeResponse);
}

// ============================================================================
// REFUND SERVICE — Manages refund status synchronization.
// ============================================================================

// Service for refund-specific operations.
service RefundService {
  // Retrieve refund status from the payment processor. Tracks refund progress
  // through processor settlement for accurate customer communication.
  rpc Get(RefundServiceGetRequest) returns (RefundResponse);

  // Void/reverse a refund before processor settlement.
  rpc VoidPostRefund(RefundServiceVoidPostRefundRequest)
      returns (RefundResponse);
}

// ============================================================================
// DISPUTE SERVICE — Manages chargeback lifecycle, evidence submission,
//                    and defense against fraudulent transaction claims.
// ============================================================================

// Service for dispute-specific operations.
service DisputeService {
  // Upload evidence to dispute customer chargeback. Provides documentation
  // like receipts and delivery proof to contest fraudulent transaction claims.
  rpc SubmitEvidence(DisputeServiceSubmitEvidenceRequest) returns (DisputeServiceSubmitEvidenceResponse);

  // Retrieve dispute status and evidence submission state. Tracks dispute
  // progress through bank review process for informed decision-making.
  rpc Get(DisputeServiceGetRequest) returns (DisputeResponse);

  // Submit defense with reason code for dispute. Presents formal argument
  // against customer's chargeback claim with supporting documentation.
  rpc Defend(DisputeServiceDefendRequest) returns (DisputeServiceDefendResponse);

  // Concede dispute and accepts chargeback loss. Acknowledges liability
  // and stops dispute defense process when evidence is insufficient.
  rpc Accept(DisputeServiceAcceptRequest) returns (DisputeServiceAcceptResponse);
}

// ============================================================================
// PAYMENT METHOD SERVICE — Manages payment method tokenization and retrieval.
// ============================================================================

service PaymentMethodService {
  // Tokenize payment method for secure storage. Replaces raw card details
  // with secure token for one-click payments and recurring billing.
  rpc Tokenize(PaymentMethodServiceTokenizeRequest) returns (PaymentMethodServiceTokenizeResponse);

  // Create payment method at connector. Establishes a new payment method and returns connector-specific details.
  rpc Create(PaymentMethodServiceCreateRequest) returns (PaymentMethodServiceCreateResponse);

  // Retrieve payment method details from the payment processor.
  rpc Get(PaymentMethodServiceGetRequest) returns (PaymentMethodServiceGetResponse);

  // Refresh a payment method the caller already holds in full. The request carries the
  // instrument itself, not a reference to it: use Refresh when you own the complete
  // payment method details and the provider exposes an endpoint that evaluates them.
  rpc Refresh(PaymentMethodServiceRefreshRequest) returns (PaymentMethodServiceRefreshResponse);

  // Recharge a payment method (wallet, gift card, prepaid card) with funds.
  rpc Recharge(PaymentMethodServiceRechargeRequest) returns (PaymentMethodServiceRechargeResponse);

  // Check if the payment method is eligible for the transaction (e.g. BNPL pre-checkout check)
  rpc Eligibility(PaymentMethodServiceEligibilityRequest) returns (PaymentMethodServiceEligibilityResponse);
}

// ============================================================================
// CUSTOMER SERVICE — Manages customer lifecycle operations.
// ============================================================================

service CustomerService {
  // Create customer record in the payment processor system. Stores customer details
  // for future payment operations without re-sending personal information.
  rpc Create(CustomerServiceCreateRequest) returns (CustomerServiceCreateResponse);

  // Retrieves customer details from the payment processor. Callers typically use
  // this before Create to implement get-or-create semantics for connectors that
  // reject duplicates (e.g. Glomopay).
  rpc Get(CustomerServiceGetRequest) returns (CustomerServiceGetResponse);

  // // Updates customer record in the payment processor system.
  // rpc Update(CustomerServiceUpdateRequest) returns (CustomerServiceUpdateResponse);

  // // Deletes customer record from the payment processor system.
  // rpc Delete(CustomerServiceDeleteRequest) returns (CustomerServiceDeleteResponse);
}

// ============================================================================
// MERCHANT AUTHENTICATION SERVICE — Manages access tokens and session initialization
//                 for secure payment processing and SDK initiation.
// ============================================================================

service MerchantAuthenticationService {
  // Generate short-lived connector authentication token. Provides secure
  // credentials for connector API access without storing secrets client-side.
  rpc CreateServerAuthenticationToken(MerchantAuthenticationServiceCreateServerAuthenticationTokenRequest) returns (MerchantAuthenticationServiceCreateServerAuthenticationTokenResponse);

  // Create a server-side session with the connector. Establishes session state
  // for multi-step operations like 3DS verification or wallet authorization.
  rpc CreateServerSessionAuthenticationToken(MerchantAuthenticationServiceCreateServerSessionAuthenticationTokenRequest) returns (MerchantAuthenticationServiceCreateServerSessionAuthenticationTokenResponse);

  // Initialize client-facing SDK sessions for wallets, device fingerprinting,
  // etc. Returns structured data the client SDK needs to render
  // payment/verification UI.
  rpc CreateClientAuthenticationToken(MerchantAuthenticationServiceCreateClientAuthenticationTokenRequest) returns (MerchantAuthenticationServiceCreateClientAuthenticationTokenResponse);
}

// ============================================================================
// PAYMENT METHOD AUTHENTICATION SERVICE — Manages 3D Secure authentication flows
//                                          for fraud prevention while balancing
//                                          checkout friction.
// ============================================================================

service PaymentMethodAuthenticationService {
  // Initiate 3DS flow before payment authorization. Collects device data and
  // prepares authentication context for frictionless or challenge-based verification.
  rpc PreAuthenticate(PaymentMethodAuthenticationServicePreAuthenticateRequest) returns (PaymentMethodAuthenticationServicePreAuthenticateResponse);

  // Execute 3DS challenge or frictionless verification. Authenticates customer
  // via bank challenge or behind-the-scenes verification for fraud prevention.
  rpc Authenticate(PaymentMethodAuthenticationServiceAuthenticateRequest) returns (PaymentMethodAuthenticationServiceAuthenticateResponse);

  // Validate authentication results with the issuing bank. Processes bank's
  // authentication decision to determine if payment can proceed.
  rpc PostAuthenticate(PaymentMethodAuthenticationServicePostAuthenticateRequest) returns (PaymentMethodAuthenticationServicePostAuthenticateResponse);
}

// ============================================================================
// PAYOUT SERVICE — Manages payout lifecycle operations.
// ============================================================================

service PayoutService {
  // Creates a payout.
  rpc Create(PayoutServiceCreateRequest) returns (PayoutServiceCreateResponse);

  // Creates a payout fund transfer.
  rpc Transfer(PayoutServiceTransferRequest) returns (PayoutServiceTransferResponse);

  // Retrieve payout details.
  rpc Get(PayoutServiceGetRequest) returns (PayoutServiceGetResponse);

  // Void a payout.
  rpc Void(PayoutServiceVoidRequest) returns (PayoutServiceVoidResponse);

  // Stage the payout.
  rpc Stage(PayoutServiceStageRequest) returns (PayoutServiceStageResponse);

  // Creates a link between the recipient and the payout.
  rpc CreateLink(PayoutServiceCreateLinkRequest) returns (PayoutServiceCreateLinkResponse);

  // Create payout recipient.
  rpc CreateRecipient(PayoutServiceCreateRecipientRequest) returns (PayoutServiceCreateRecipientResponse);

  // Enroll disburse account.
  rpc EnrollDisburseAccount(PayoutServiceEnrollDisburseAccountRequest) returns (PayoutServiceEnrollDisburseAccountResponse);

  // Check eligibility of a payout before initiating it (e.g. SEPA VoP / payee verification).
  rpc Eligibility(PayoutMethodEligibilityRequest) returns (PayoutMethodEligibilityResponse);
}

// ============================================================================
// SURCHARGE SERVICE — Calculates payment processing fees 
// ============================================================================

service SurchargeService {
  // Calculate surcharge fees for a payment amount before processing.
  rpc Calculate(SurchargeServiceCalculateRequest) returns (SurchargeServiceCalculateResponse);
}

// ============================================================================
// FRAUD AND RISK MANAGEMENT SERVICE -- Evaluates transactions for fraud
//                                          risk before and after payment processing.
// ============================================================================

service FraudAndRiskManagementService {
  // Evaluate fraud risk before payment processing. Analyzes transaction details,
  // customer behavior, and device fingerprints to determine if the payment
  // should proceed, be rejected, or flagged for manual review.
  rpc PreRiskCheck(FrmServicePreRiskCheckRequest) returns (FrmServicePreRiskCheckResponse);

  // Evaluate fraud risk after payment processing. Analyzes payment outcomes
  // and post-transaction signals to refine risk models and detect chargeback fraud.
  rpc PostRiskCheck(FrmServicePostRiskCheckRequest) returns (FrmServicePostRiskCheckResponse);
}

