import type { IRestApiContext } from '../types';
import { get, post } from '../utils';

export declare namespace Cloud {
	export interface PlanData {
		planId: number;
		monthlyExecutionsLimit: number;
		activeWorkflowsLimit: number;
		credentialsLimit: number;
		isActive: boolean;
		displayName: string;
		expirationDate: string;
		metadata: PlanMetadata;
		userIsTrialing?: boolean;
		bannerConfig?: BannerConfig;
	}

	export interface PlanMetadata {
		version: 'v1';
		group: 'opt-out' | 'opt-in' | 'trial';
		slug: 'pro-1' | 'pro-2' | 'starter' | 'trial-1';
		trial?: Trial;
	}

	interface Trial {
		length: number;
		gracePeriod: number;
	}

	export interface BannerConfig {
		// If set, show time left section
		// - If text provided, use it
		// - If text not provided, compute from expirationDate
		timeLeft?: {
			text?: string;
		};

		// If true, show executions section with progress bar and x/y text
		showExecutions?: boolean;

		// CTA button configuration
		cta?: {
			text?: string;
			icon?: string;
			size?: 'small' | 'medium';
			/** @deprecated Use variant instead */
			style?: 'primary' | 'success' | 'warning' | 'danger';
			variant?: 'solid' | 'subtle' | 'ghost' | 'outline' | 'destructive' | 'success';
			href?: string; // If provided, navigate to this URL; otherwise use upgrade flow
		};

		// Banner icon (left side) - if not set, no icon shown
		icon?: string;

		dismissible?: boolean;
		forceShow?: boolean; // Override localStorage dismissal
	}

	export type UserAccount = {
		confirmed: boolean;
		username: string;
		email: string;
		hasEarlyAccess?: boolean;
		role?: string;
		selectedApps?: string[];
		information?: {
			[key: string]: string | string[];
		};
	};
}

export interface InstanceUsage {
	timeframe?: string;
	executions: number;
	activeWorkflows: number;
}

export async function getCurrentPlan(context: IRestApiContext): Promise<Cloud.PlanData> {
	return await get(context.baseUrl, '/admin/cloud-plan');
}

export async function getCurrentUsage(context: IRestApiContext): Promise<InstanceUsage> {
	return await get(context.baseUrl, '/cloud/limits');
}

export async function getCloudUserInfo(context: IRestApiContext): Promise<Cloud.UserAccount> {
	return await get(context.baseUrl, '/cloud/proxy/user/me');
}

export async function sendConfirmationEmail(context: IRestApiContext): Promise<Cloud.UserAccount> {
	return await post(context.baseUrl, '/cloud/proxy/user/resend-confirmation-email');
}

export async function getAdminPanelLoginCode(context: IRestApiContext): Promise<{ code: string }> {
	return await get(context.baseUrl, '/cloud/proxy/login/code');
}

export interface DynamicNotification {
	title?: string;
	message?: string;
}

export async function sendUserEvent(
	context: IRestApiContext,
	eventData: { eventType: string; metadata?: Record<string, unknown> },
): Promise<DynamicNotification> {
	return await post(context.baseUrl, '/cloud/proxy/user/event', eventData);
}
