// ================================================================
// frontend/src/api/types/auth.ts
// ================================================================
/**
 * Authentication Type Definitions
 *
 * Aligned with backend schemas:
 * - services/auth/app/schemas/auth.py
 * - services/auth/app/schemas/users.py
 *
 * Last Updated: 2025-01-14
 * Status: Complete - Atomic registration flow with 3DS support
 */

// ================================================================
// REQUEST TYPES
// ================================================================

/**
 * User registration request
 * Backend: services/auth/app/schemas/auth.py:15-29 (UserRegistration)
 * Updated for new atomic registration flow with 3DS support
 */
export interface UserRegistration {
  email: string;  // EmailStr - validated email format
  password: string;  // min_length=8, max_length=128
  full_name: string;  // min_length=1, max_length=255
  tenant_name?: string | null;  // max_length=255
  role?: string | null;  // Default: "admin", pattern: ^(user|admin|manager|super_admin)$
  subscription_plan?: string | null;  // Default: "starter", options: starter, professional, enterprise
  billing_cycle?: 'monthly' | 'yearly' | null;  // Default: "monthly" - Billing cycle preference
  payment_method_id?: string | null;  // Stripe payment method ID
  coupon_code?: string | null;  // Promotional coupon code for discounts/trial extensions
  // Payment setup data (passed to complete-registration after 3DS)
  customer_id?: string | null;  // Stripe customer ID from payment setup
  trial_period_days?: number | null;  // Trial period from coupon
  // GDPR Consent fields
  terms_accepted?: boolean;  // Default: true - Accept terms of service
  privacy_accepted?: boolean;  // Default: true - Accept privacy policy
  marketing_consent?: boolean;  // Default: false - Consent to marketing communications
  analytics_consent?: boolean;  // Default: false - Consent to analytics cookies
  // Billing address fields for subscription creation
  address?: string | null;  // Billing address
  postal_code?: string | null;  // Billing postal code
  city?: string | null;  // Billing city
  country?: string | null;  // Billing country
}

/**
 * Registration verification data for 3DS completion
 * Used in the second step of the atomic registration flow
 */
export interface RegistrationVerification {
  setup_intent_id: string;  // SetupIntent ID from first step
  user_data: UserRegistration;  // Original user registration data
  state_id?: string | null;  // Optional registration state ID for tracking
}

/**
 * Registration start response (first step)
 * Response from /start-registration endpoint
 * Backend: services/auth/app/api/auth_operations.py:start_registration()
 */
export interface RegistrationStartResponse {
  requires_action: boolean;  // Whether 3DS/SetupIntent authentication is required
  action_type?: string | null;  // Type of action required (e.g., 'setup_intent_confirmation')
  client_secret?: string | null;  // Client secret for SetupIntent authentication
  setup_intent_id?: string | null;  // SetupIntent ID for 3DS authentication
  customer_id?: string | null;  // Stripe customer ID
  payment_customer_id?: string | null;  // Payment customer ID
  plan_id?: string | null;  // Plan ID
  payment_method_id?: string | null;  // Payment method ID
  billing_cycle?: string | null;  // Billing cycle
  trial_period_days?: number | null;  // Trial period from coupon (e.g., 90 for PILOT2025)
  email?: string | null;  // User email
  state_id?: string | null;  // Registration state ID for tracking
  message?: string | null;  // Message explaining what needs to be done
  user?: UserData | null;  // User data (only if no 3DS required)
  subscription_id?: string | null;  // Subscription ID (only if no 3DS required)
  status?: string | null;  // Status (only if no 3DS required)
}

/**
 * Registration completion response (second step)
 * Response from /complete-registration endpoint
 * Backend: services/auth/app/api/auth_operations.py:complete_registration()
 */
export interface RegistrationCompletionResponse {
  success: boolean;  // Whether registration was successful
  user?: UserData | null;  // Created user data
  subscription_id?: string | null;  // Created subscription ID
  payment_customer_id?: string | null;  // Payment customer ID
  status?: string | null;  // Subscription status
  message?: string | null;  // Success/error message
  access_token?: string | null;  // JWT access token
  refresh_token?: string | null;  // JWT refresh token
}

/**
 * User login request
 * Backend: services/auth/app/schemas/auth.py:26-29 (UserLogin)
 */
export interface UserLogin {
  email: string;  // EmailStr - validated email format
  password: string;
}

/**
 * Refresh token request
 * Backend: services/auth/app/schemas/auth.py:31-33 (RefreshTokenRequest)
 */
export interface RefreshTokenRequest {
  refresh_token: string;
}

/**
 * Password change request
 * Backend: services/auth/app/schemas/auth.py:35-38 (PasswordChange)
 */
export interface PasswordChange {
  current_password: string;
  new_password: string;  // min_length=8, max_length=128
}

/**
 * Password reset request (initiate reset)
 * Backend: services/auth/app/schemas/auth.py:40-42 (PasswordReset)
 */
export interface PasswordReset {
  email: string;  // EmailStr - validated email format
}

/**
 * Password reset confirmation (complete reset)
 * Backend: services/auth/app/schemas/auth.py:44-47 (PasswordResetConfirm)
 */
export interface PasswordResetConfirm {
  token: string;
  new_password: string;  // min_length=8, max_length=128
}

/**
 * Email verification request
 * Backend: services/auth/app/schemas/auth.py:173-175 (EmailVerificationRequest)
 */
export interface EmailVerificationRequest {
  email: string;  // EmailStr - validated email format
}

/**
 * Email verification confirmation
 * Backend: services/auth/app/schemas/auth.py:177-179 (EmailVerificationConfirm)
 */
export interface EmailVerificationConfirm {
  token: string;
}

/**
 * Profile update request
 * Backend: services/auth/app/schemas/auth.py:181-184 (ProfileUpdate)
 */
export interface ProfileUpdate {
  full_name?: string | null;  // min_length=1, max_length=255
  email?: string | null;  // EmailStr - validated email format
}

/**
 * User update schema
 * Backend: services/auth/app/schemas/users.py:14-26 (UserUpdate)
 */
export interface UserUpdate {
  full_name?: string | null;  // min_length=2, max_length=100
  phone?: string | null;  // Spanish phone validation applied on backend
  language?: string | null;  // pattern: ^(es|en)$
  timezone?: string | null;
}

// ================================================================
// RESPONSE TYPES
// ================================================================

/**
 * User data embedded in token responses
 * Backend: services/auth/app/schemas/auth.py:53-62 (UserData)
 */
export interface UserData {
  id: string;
  email: string;
  full_name: string;
  is_active: boolean;
  is_verified: boolean;
  created_at: string;  // ISO format datetime string
  tenant_id?: string | null;
  role?: string | null;  // Default: "admin"
}

/**
 * Unified token response for both registration and login
 * Follows industry standards (Firebase, AWS Cognito, etc.)
 * Backend: services/auth/app/schemas/auth.py:64-92 (TokenResponse)
 */
export interface TokenResponse {
  access_token: string;
  refresh_token?: string | null;
  token_type: string;  // Default: "bearer"
  expires_in: number;  // Default: 3600 seconds
  user?: UserData | null;
}

/**
 * User response for user management endpoints
 * Backend: services/auth/app/schemas/auth.py:94-110 (UserResponse)
 */
export interface UserResponse {
  id: string;
  email: string;
  full_name: string;
  is_active: boolean;
  is_verified: boolean;
  created_at: string;  // ISO datetime string
  last_login?: string | null;  // ISO datetime string
  phone?: string | null;
  language?: string | null;
  timezone?: string | null;
  tenant_id?: string | null;
  role?: string | null;  // Default: "admin"
  payment_customer_id?: string | null;  // Payment provider customer ID (Stripe, etc.)
  default_payment_method_id?: string | null;  // Default payment method ID
}

/**
 * User profile schema
 * Backend: services/auth/app/schemas/users.py:28-42 (UserProfile)
 */
export interface UserProfile {
  id: string;
  email: string;
  full_name: string;
  phone?: string | null;
  language: string;
  timezone: string;
  is_active: boolean;
  is_verified: boolean;
  created_at: string;  // ISO datetime string
  last_login?: string | null;  // ISO datetime string
}

/**
 * Token verification response
 * Backend: services/auth/app/schemas/auth.py:123-129 (TokenVerification)
 */
export interface TokenVerification {
  valid: boolean;
  user_id?: string | null;
  email?: string | null;
  exp?: number | null;  // Expiration timestamp
  message?: string | null;
}

/**
 * Token verification response (alias for hooks)
 */
export type TokenVerificationResponse = TokenVerification;

/**
 * Password reset response
 * Backend: services/auth/app/schemas/auth.py:131-134 (PasswordResetResponse)
 */
export interface PasswordResetResponse {
  message: string;
  reset_token?: string | null;
}

/**
 * Logout response
 * Backend: services/auth/app/schemas/auth.py:136-139 (LogoutResponse)
 */
export interface LogoutResponse {
  message: string;
  success: boolean;  // Default: true
}

/**
 * Auth health response
 */
export interface AuthHealthResponse {
  status: string;
  service: string;
  version?: string;
  features?: string[];
}

// ================================================================
// ERROR TYPES
// ================================================================

/**
 * Error detail for API responses
 * Backend: services/auth/app/schemas/auth.py:145-149 (ErrorDetail)
 */
export interface ErrorDetail {
  message: string;
  code?: string | null;
  field?: string | null;
}

/**
 * Standardized error response
 * Backend: services/auth/app/schemas/auth.py:151-167 (ErrorResponse)
 */
export interface ErrorResponse {
  success: boolean;  // Default: false
  error: ErrorDetail;
  timestamp: string;  // ISO datetime string
}

// ================================================================
// INTERNAL TYPES (for service communication)
// ================================================================

/**
 * User context for internal service communication
 * Backend: services/auth/app/schemas/auth.py:190-196 (UserContext)
 */
export interface UserContext {
  user_id: string;
  email: string;
  tenant_id?: string | null;
  roles: string[];  // Default: ["admin"]
  is_verified: boolean;  // Default: false
}

/**
 * JWT token claims structure
 * Backend: services/auth/app/schemas/auth.py:198-208 (TokenClaims)
 */
export interface TokenClaims {
  sub: string;  // subject (user_id)
  email: string;
  full_name: string;
  user_id: string;
  is_verified: boolean;
  tenant_id?: string | null;
  iat: number;  // issued at timestamp
  exp: number;  // expires at timestamp
  iss: string;  // issuer - Default: "bakery-auth"
}

// ================================================================
// 3DS Authentication Types
// ================================================================

/**
 * Exception thrown when 3DS authentication is required
 * This is used in the SetupIntent-first registration flow
 */
export class ThreeDSAuthenticationRequired extends Error {
  constructor(
    public setup_intent_id: string,
    public client_secret: string,
    public action_type: string,
    message: string = "3DS authentication required",
    public extra_data: Record<string, unknown> = {}
  ) {
    super(message);
    this.name = "ThreeDSAuthenticationRequired";
  }
}
