/**
 * TypeScript types for Tenant service
 * Mirrored from backend schemas: services/tenant/app/schemas/tenants.py
 *
 * Coverage:
 * - Bakery Registration (onboarding flow)
 * - Tenant CRUD (tenant management)
 * - Tenant Members (team management, invitations)
 * - Subscriptions (plan management)
 * - Access Control (permissions, roles)
 * - Analytics (statistics, search)
 */

import type { TenantRole } from '../../types/roles';

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

/**
 * Bakery registration schema
 * Backend: BakeryRegistration in schemas/tenants.py (lines 12-53)
 */
export interface BakeryRegistration {
  name: string;  // min_length=2, max_length=200
  address: string;  // min_length=10, max_length=500
  city?: string;  // Default: "Madrid", max_length=100
  postal_code: string;  // pattern: ^\d{5}$
  phone: string;  // min_length=9, max_length=20 - Spanish phone validation
  business_type?: string;  // Default: "bakery" - one of: bakery, coffee_shop, pastry_shop, restaurant
  business_model?: string | null;  // Default: "individual_bakery" - one of: individual_bakery, central_baker_satellite, retail_bakery, hybrid_bakery
}

/**
 * Tenant update schema
 * Backend: TenantUpdate in schemas/tenants.py (lines 109-115)
 */
export interface TenantUpdate {
  name?: string | null;  // min_length=2, max_length=200
  address?: string | null;  // min_length=10, max_length=500
  phone?: string | null;
  business_type?: string | null;
  business_model?: string | null;
  // Regional/Localization settings
  currency?: string | null;  // Currency code (EUR, USD, GBP)
  timezone?: string | null;
  language?: string | null;
}

/**
 * Tenant search request schema
 * Backend: TenantSearchRequest in schemas/tenants.py (lines 160-167)
 */
export interface TenantSearchRequest {
  query?: string | null;
  business_type?: string | null;
  city?: string | null;
  status?: string | null;
  limit?: number;  // Default: 50, ge=1, le=100
  offset?: number;  // Default: 0, ge=0
}

/**
 * Schema for inviting a member to a tenant
 * Backend: TenantMemberInvitation in schemas/tenants.py (lines 126-130)
 */
export interface TenantMemberInvitation {
  email: string;  // pattern: ^[^@]+@[^@]+\.[^@]+$
  role: 'admin' | 'member' | 'viewer';
  message?: string | null;  // max_length=500
}

/**
 * Schema for updating tenant member
 * Backend: TenantMemberUpdate in schemas/tenants.py (lines 137-140)
 */
export interface TenantMemberUpdate {
  role?: 'owner' | 'admin' | 'member' | 'viewer' | null;
  is_active?: boolean | null;
}

/**
 * Schema for adding member with optional user creation (pilot phase)
 * Backend: AddMemberWithUserCreate in schemas/tenants.py (lines 142-174)
 */
export interface AddMemberWithUserCreate {
  // For existing users
  user_id?: string | null;

  // For new user creation
  create_user?: boolean;  // Default: false
  email?: string | null;
  full_name?: string | null;
  password?: string | null;
  phone?: string | null;
  language?: 'es' | 'en' | 'eu';  // Default: "es"
  timezone?: string;  // Default: "Europe/Madrid"

  // Common fields
  role: 'admin' | 'member' | 'viewer';
}

/**
 * Schema for updating tenant subscription
 * Backend: TenantSubscriptionUpdate in schemas/tenants.py (lines 137-140)
 */
export interface TenantSubscriptionUpdate {
  plan: 'basic' | 'professional' | 'enterprise';
  billing_cycle?: 'monthly' | 'yearly';  // Default: "monthly"
}

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

/**
 * Tenant response schema - Updated with subscription_plan
 * Backend: TenantResponse in schemas/tenants.py (lines 59-87)
 */
export interface TenantResponse {
  id: string;
  name: string;
  subdomain?: string | null;
  business_type: string;
  business_model?: string | null;
  address: string;
  city: string;
  postal_code: string;
  phone?: string | null;
  is_active: boolean;
  subscription_plan?: string | null;  // Populated from subscription relationship
  ml_model_trained: boolean;
  last_training_date?: string | null;  // ISO datetime string
  owner_id: string;  // ✅ REQUIRED field
  created_at: string;  // ISO datetime string

  // Regional/Localization settings
  currency?: string | null;  // Default: 'EUR' - Currency code (EUR, USD, GBP)
  timezone?: string | null;  // Default: 'Europe/Madrid'
  language?: string | null;  // Default: 'es'

  // Backward compatibility
  /** @deprecated Use subscription_plan instead */
  subscription_tier?: string;
}

/**
 * Tenant access verification response
 * Backend: TenantAccessResponse in schemas/tenants.py (lines 84-88)
 */
export interface TenantAccessResponse {
  has_access: boolean;
  role: string;
  permissions: string[];
}

/**
 * Tenant member response - FIXED VERSION with enriched user data
 * Backend: TenantMemberResponse in schemas/tenants.py (lines 91-112)
 */
export interface TenantMemberResponse {
  id: string;
  user_id: string;
  role: string;
  is_active: boolean;
  joined_at?: string | null;  // ISO datetime string
  // Enriched user fields (populated via service layer)
  user_email?: string | null;
  user_full_name?: string | null;
  user?: any;  // Full user object for compatibility
}

/**
 * Response schema for listing tenants
 * Backend: TenantListResponse in schemas/tenants.py (lines 117-124)
 */
export interface TenantListResponse {
  tenants: TenantResponse[];
  total: number;
  page: number;
  per_page: number;
  has_next: boolean;
  has_prev: boolean;
}

/**
 * Tenant statistics response
 * Backend: TenantStatsResponse in schemas/tenants.py (lines 142-158)
 */
export interface TenantStatsResponse {
  tenant_id: string;
  total_members: number;
  active_members: number;
  total_predictions: number;
  models_trained: number;
  last_training_date?: string | null;  // ISO datetime string
  subscription_plan: string;
  subscription_status: string;
}

// ================================================================
// SUBSCRIPTION TYPES
// ================================================================

/**
 * Subscription plan tiers
 * Used in TenantResponse.subscription_tier and related endpoints
 */
export type SubscriptionPlan = 'basic' | 'professional' | 'enterprise';

/**
 * Subscription billing cycles
 */
export type BillingCycle = 'monthly' | 'yearly';

/**
 * Subscription status values
 */
export type SubscriptionStatus = 'active' | 'inactive' | 'cancelled' | 'expired' | 'trial';

// ================================================================
// LEGACY/COMPATIBILITY TYPES (for gradual migration)
// ================================================================

/**
 * @deprecated Use TenantSearchRequest instead
 */
export interface TenantSearchParams {
  search_term?: string;
  business_type?: string;
  city?: string;
  skip?: number;
  limit?: number;
}

/**
 * @deprecated Use TenantStatsResponse instead
 */
export interface TenantStatistics {
  total_tenants: number;
  active_tenants: number;
  inactive_tenants: number;
  tenants_by_business_type: Record<string, number>;
  tenants_by_city: Record<string, number>;
  recent_registrations: TenantResponse[];
}

/**
 * Geolocation query parameters for nearby tenant search
 * Note: Not in backend schemas - may be deprecated
 */
export interface TenantNearbyParams {
  latitude: number;
  longitude: number;
  radius_km?: number;
  limit?: number;
}

// ================================================================
// NEW ARCHITECTURE: TENANT-INDEPENDENT SUBSCRIPTION TYPES
// ================================================================

/**
 * Subscription linking request for new registration flow
 * Backend: services/tenant/app/api/tenant_operations.py
 */
export interface SubscriptionLinkingRequest {
  tenant_id: string;  // Tenant ID to link subscription to
  subscription_id: string;  // Subscription ID to link
  user_id: string;  // User ID performing the linking
}

/**
 * Subscription linking response
 */
export interface SubscriptionLinkingResponse {
  success: boolean;
  message: string;
  data?: {
    tenant_id: string;
    subscription_id: string;
    status: string;
  };
}

/**
 * Extended BakeryRegistration with subscription linking support
 */
export interface BakeryRegistrationWithSubscription extends BakeryRegistration {
  subscription_id?: string | null;  // Optional subscription ID to link
  link_existing_subscription?: boolean | null;  // Flag to link existing subscription
}
