/**
 * User Management Types
 *
 * Type definitions for user management feature including:
 * - DTOs (Data Transfer Objects)
 * - API request/response types
 * - Database model types
 * - Filter and query types
 *
 * @module types/user-management
 */

// ============================================
// ENUMS
// ============================================

export type AccountStatus = 'active' | 'suspended' | 'locked' | 'inactive';
export type UserRole = 'CUSTOMER' | 'STAFF' | 'ADMIN' | 'SUPER_ADMIN';
export type UserStatus = 'all' | 'active' | 'suspended' | 'locked';
export type NoteCategory = 'GENERAL' | 'BILLING' | 'SUPPORT' | 'COMPLIANCE' | 'TECHNICAL' | 'SALES';
export type EmailStatus = 'DRAFT' | 'SENT' | 'OPENED' | 'PAID' | 'OVERDUE' | 'CANCELLED';
export type LoginProvider = 'credentials' | 'google' | 'staff-credentials';

// ============================================
// USER TYPES
// ============================================

/**
 * Basic user information for listings
 */
export interface UserListItem {
  id: string;
  name: string;
  email: string;
  role: UserRole;
  country: string | null;
  city: string | null;
  companyName: string | null;
  industry: string | null;
  selectedPackage: string | null;
  lastLoginAt: Date | null;
  lastLoginIp: string | null;
  lastLoginCountry: string | null;
  lastLoginCity: string | null;
  loginCount: number;
  isActive: boolean;
  isSuspended: boolean;
  suspendedAt: Date | null;
  suspendedReason: string | null;
  lockedUntil: Date | null;
  createdAt: Date;
  accountStatus: AccountStatus;
  hasSubscription: boolean;
  _count: {
    adminNotes: number;
    billingEmails: number;
    subscriptions: number;
    loginHistory: number;
  };
}

/**
 * Complete user details with all relations
 */
export interface UserDetails extends Omit<UserListItem, 'accountStatus' | 'hasSubscription'> {
  subscriptions: Subscription[];
  adminNotes: AdminNote[];
  billingEmails: BillingEmail[];
  loginHistory: LoginHistoryEntry[];
  auditLogs: AuditLog[];
}

// ============================================
// QUERY TYPES
// ============================================

/**
 * Query parameters for user listing
 */
export interface UserListQuery {
  /** Search term for name, email, company */
  search?: string;
  /** Filter by account status */
  status?: UserStatus;
  /** Filter by user role */
  role?: UserRole | 'all';
  /** Filter by country */
  country?: string;
  /** Page number (1-indexed) */
  page?: number;
  /** Items per page (max 100) */
  limit?: number;
  /** Field to sort by */
  sortBy?: 'createdAt' | 'lastLoginAt' | 'loginCount' | 'email' | 'name';
  /** Sort direction */
  sortOrder?: 'asc' | 'desc';
}

/**
 * Pagination metadata
 */
export interface PaginationMeta {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
  hasMore: boolean;
}

/**
 * User analytics data
 */
export interface UserAnalytics {
  total: number;
  active: number;
  suspended: number;
  locked: number;
  newThisWeek: number;
  activeSubscriptions: number;
  byCountry: Record<string, number>;
  byIndustry: Record<string, number>;
  byPackage: Record<string, number>;
}

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

/**
 * Response for user listing endpoint
 */
export interface UserListResponse {
  users: UserListItem[];
  analytics: UserAnalytics;
  pagination: PaginationMeta;
}

/**
 * Response for user details endpoint
 */
export interface UserDetailsResponse {
  user: Omit<UserDetails, 'password'>;
  analytics: {
    loginStats: {
      total: number;
      successful: number;
      failed: number;
      successRate: number;
      uniqueIps: number;
      uniqueCountries: number;
      recentCountries: Array<{
        country: string | null;
        city: string | null;
        timestamp: Date;
      }>;
    };
    billingStats?: {
      total: number;
      paid: number;
      overdue: number;
    };
    activityStats?: {
      adminNotes: number;
      auditLogs: number;
      subscriptions: number;
    };
  };
}

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

/**
 * Request to update account status
 */
export interface AccountStatusUpdate {
  /** Action to perform */
  action: 'suspend' | 'activate';
  /** Reason for action (min 5 chars) */
  reason: string;
}

/**
 * Request to create admin note
 */
export interface CreateAdminNoteRequest {
  /** Note content (5-5000 chars) */
  content: string;
  /** Note category */
  category: NoteCategory;
  /** Whether note is private (default true) */
  isPrivate?: boolean;
}

/**
 * Request to send billing email
 */
export interface SendBillingEmailRequest {
  /** Email subject (min 5 chars) */
  subject: string;
  /** Email body (min 10 chars) */
  content: string;
  /** Optional billing amount */
  amount?: number;
  /** Optional due date */
  dueDate?: string;
}

// ============================================
// MODEL TYPES
// ============================================

/**
 * Admin note data
 */
export interface AdminNote {
  id: string;
  userId: string;
  staffId: string;
  content: string;
  category: NoteCategory;
  isPrivate: boolean;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * Billing email data
 */
export interface BillingEmail {
  id: string;
  userId: string;
  staffId: string;
  subject: string;
  body: string;
  amount: number | null;
  dueDate: Date | null;
  status: EmailStatus;
  sentAt: Date;
  openedAt: Date | null;
  paidAt: Date | null;
}

/**
 * Login history entry
 */
export interface LoginHistoryEntry {
  id: string;
  userId: string;
  ipAddress: string;
  userAgent: string | null;
  country: string | null;
  countryCode: string | null;
  city: string | null;
  region: string | null;
  latitude: number | null;
  longitude: number | null;
  timezone: string | null;
  provider: LoginProvider;
  success: boolean;
  failReason: string | null;
  createdAt: Date;
}

/**
 * Subscription data (simplified for user management)
 */
export interface Subscription {
  id: string;
  userId: string;
  status: string;
  tierId: string;
  billingPeriod: string;
  currentPeriodEnd: Date;
  createdAt: Date;
}

/**
 * Audit log entry (simplified)
 */
export interface AuditLog {
  id: string;
  userId: string | null;
  type: string;
  action: string;
  success: boolean;
  ip: string;
  metadata: any;
  createdAt: Date;
}

// ============================================
// VALIDATION TYPES
// ============================================

/**
 * Validation rules for user management
 */
export const ValidationRules = {
  note: {
    minLength: 5,
    maxLength: 5000,
  },
  suspension: {
    reasonMinLength: 5,
  },
  billing: {
    subjectMinLength: 5,
    subjectMaxLength: 200,
    contentMinLength: 10,
    contentMaxLength: 10000,
  },
  pagination: {
    maxLimit: 100,
    defaultLimit: 50,
  },
} as const;

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

/**
 * User management specific errors
 */
export class UserManagementError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 400
  ) {
    super(message);
    this.name = 'UserManagementError';
  }
}

/**
 * Common error codes
 */
export const ErrorCodes = {
  USER_NOT_FOUND: 'USER_NOT_FOUND',
  UNAUTHORIZED: 'UNAUTHORIZED',
  FORBIDDEN: 'FORBIDDEN',
  INVALID_ACTION: 'INVALID_ACTION',
  INVALID_INPUT: 'INVALID_INPUT',
  CANNOT_SUSPEND_ADMIN: 'CANNOT_SUSPEND_ADMIN',
  REASON_TOO_SHORT: 'REASON_TOO_SHORT',
  CONTENT_TOO_SHORT: 'CONTENT_TOO_SHORT',
  CONTENT_TOO_LONG: 'CONTENT_TOO_LONG',
  INVALID_CATEGORY: 'INVALID_CATEGORY',
} as const;

// ============================================
// FILTER TYPES
// ============================================

/**
 * User filters for frontend
 */
export interface UserFilters {
  search: string;
  status: UserStatus;
  role: UserRole | 'all';
  country: string;
}

/**
 * Geography data for map view
 */
export interface GeographyData {
  country: string;
  count: number;
  percentage: number;
  latitude?: number;
  longitude?: number;
}

// ============================================
// STATS TYPES
// ============================================

/**
 * User statistics for dashboard
 */
export interface UserStats {
  total: number;
  active: number;
  suspended: number;
  locked: number;
  topCountry: { name: string; count: number } | null;
  topIndustry: { name: string; count: number } | null;
}

/**
 * Login analytics
 */
export interface LoginAnalytics {
  totalLogins: number;
  uniqueIPs: number;
  uniqueCountries: number;
  successfulLogins: number;
  failedLogins: number;
  successRate: number;
  recentCountries: string[];
}

// ============================================
// UTILITY TYPES
// ============================================

/**
 * User without sensitive data (for API responses)
 */
export type SafeUser = Omit<UserDetails, 'password'>;

/**
 * Partial user for updates
 */
export type UserUpdate = Partial<
  Pick<
    UserDetails,
    | 'name'
    | 'companyName'
    | 'industry'
    | 'phoneNumber'
    | 'isActive'
    | 'isSuspended'
    | 'suspendedReason'
  >
>;
