/**
 * Stripe Connect Module
 *
 * Handles connected account creation, onboarding, and platform fee collection.
 * Mawidi earns 1.5% on deposits processed through connected accounts.
 */

import { stripe } from './client';
import { convexMutation } from '@/lib/convex-client';
import { logger } from '@/lib/logger';

/**
 * Create a Stripe Connect Express account for a merchant organization
 */
export async function createConnectedAccount(
  orgId: string,
  businessInfo: {
    businessName: string;
    email: string;
    country: string; // ISO 2-letter: SA, AE, QA, etc.
  }
): Promise<{ accountId: string; onboardingUrl: string }> {
  // Create Express account
  const account = await stripe.accounts.create({
    type: 'express',
    country: businessInfo.country,
    email: businessInfo.email,
    business_type: 'company',
    company: { name: businessInfo.businessName },
    capabilities: {
      card_payments: { requested: true },
      transfers: { requested: true },
    },
    metadata: { organization_id: orgId },
  });

  await convexMutation("organizations/mutations:updateOrganizationNoAuth", {
    organizationId: orgId,
    stripeConnectAccountId: account.id,
    stripeConnectStatus: "pending",
  });

  // Create account link for onboarding
  const accountLink = await createAccountLink(account.id);

  logger.info('Stripe Connect account created', { orgId, accountId: account.id });
  return { accountId: account.id, onboardingUrl: accountLink };
}

/**
 * Create an account link for Stripe Connect onboarding
 */
export async function createAccountLink(accountId: string): Promise<string> {
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';
  const lang = 'en'; // Default to English for onboarding

  const accountLink = await stripe.accountLinks.create({
    account: accountId,
    refresh_url: `${appUrl}/${lang}/dashboard/settings/stripe-connect?refresh=true`,
    return_url: `${appUrl}/${lang}/dashboard/settings/stripe-connect?success=true`,
    type: 'account_onboarding',
  });

  return accountLink.url;
}

/**
 * Get the status of a connected account
 */
export async function getAccountStatus(accountId: string): Promise<{
  status: 'pending' | 'active' | 'restricted' | 'disabled';
  chargesEnabled: boolean;
  payoutsEnabled: boolean;
  detailsSubmitted: boolean;
  requirements: string[];
}> {
  const account = await stripe.accounts.retrieve(accountId);

  let status: 'pending' | 'active' | 'restricted' | 'disabled' = 'pending';
  if (account.charges_enabled && account.payouts_enabled) {
    status = 'active';
  } else if (account.details_submitted) {
    status = 'restricted';
  }

  return {
    status,
    chargesEnabled: account.charges_enabled ?? false,
    payoutsEnabled: account.payouts_enabled ?? false,
    detailsSubmitted: account.details_submitted ?? false,
    requirements: account.requirements?.currently_due || [],
  };
}

/**
 * Calculate platform fee for a deposit amount
 * Platform fee: 1.5% of the deposit
 */
export function calculatePlatformFee(amountInCents: number): number {
  return Math.round(amountInCents * 0.015); // 1.5%
}

/**
 * Retrieve platform fee details for a payment intent with Connect
 * Used to verify/audit platform fees collected on deposits
 */
export async function getDepositPlatformFee(paymentIntentId: string): Promise<{
  paymentIntentId: string;
  totalAmount: number;
  platformFee: number;
  netToMerchant: number;
  currency: string;
  connectedAccountId: string | null;
} | null> {
  try {
    const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);

    if (!paymentIntent.application_fee_amount) {
      return null;
    }

    return {
      paymentIntentId: paymentIntent.id,
      totalAmount: paymentIntent.amount,
      platformFee: paymentIntent.application_fee_amount,
      netToMerchant: paymentIntent.amount - paymentIntent.application_fee_amount,
      currency: paymentIntent.currency,
      connectedAccountId: (paymentIntent.transfer_data?.destination as string) || null,
    };
  } catch (error) {
    logger.error('Failed to retrieve deposit platform fee', { paymentIntentId, error });
    return null;
  }
}

/**
 * Create a Stripe login link for the merchant's Express dashboard
 */
export async function createDashboardLink(accountId: string): Promise<string> {
  const loginLink = await stripe.accounts.createLoginLink(accountId);
  return loginLink.url;
}
