/**
 * @ai-summary TypeScript types for admin feature
 * @ai-context Mirrors backend admin types for frontend use
 */

// Admin user types
export interface AdminUser {
  auth0Sub: string;
  email: string;
  role: string;
  createdAt: string;
  createdBy: string;
  revokedAt: string | null;
  updatedAt: string;
}

export interface CreateAdminRequest {
  email: string;
  role?: string;
}

// Admin audit log types
export interface AdminAuditLog {
  id: string;
  actorAdminId: string;
  targetAdminId: string | null;
  action: string;
  resourceType: string | null;
  resourceId: string | null;
  context: Record<string, any> | null;
  createdAt: string;
}

// Platform catalog types
export interface CatalogMake {
  id: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}

export interface CatalogModel {
  id: string;
  makeId: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}

export interface CatalogYear {
  id: string;
  modelId: string;
  year: number;
  createdAt: string;
  updatedAt: string;
}

export interface CatalogTrim {
  id: string;
  yearId: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}

export interface CatalogEngine {
  id: string;
  trimId: string;
  name: string;
  displacement: string | null;
  cylinders: number | null;
  fuelType: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface CreateCatalogMakeRequest {
  name: string;
}

export interface UpdateCatalogMakeRequest {
  name: string;
}

export interface CreateCatalogModelRequest {
  makeId: string;
  name: string;
}

export interface UpdateCatalogModelRequest {
  name: string;
}

export interface CreateCatalogYearRequest {
  modelId: string;
  year: number;
}

export interface UpdateCatalogYearRequest {
  modelId: string;
  year: number;
}

export interface CreateCatalogTrimRequest {
  yearId: string;
  name: string;
}

export interface UpdateCatalogTrimRequest {
  name: string;
}

export interface CreateCatalogEngineRequest {
  trimId: string;
  name: string;
  displacement?: string;
  cylinders?: number;
  fuelType?: string;
}

export interface UpdateCatalogEngineRequest {
  name?: string;
  displacement?: string;
  cylinders?: number;
  fuelType?: string;
}

// Admin access verification
export interface AdminAccessResponse {
  isAdmin: boolean;
  adminRecord: AdminUser | null;
}

// Catalog search types
export interface CatalogSearchResult {
  id: number;
  year: number;
  make: string;
  model: string;
  trim: string;
  engineId: number | null;
  engineName: string | null;
  transmissionId: number | null;
  transmissionType: string | null;
}

export interface CatalogSearchResponse {
  items: CatalogSearchResult[];
  total: number;
  page: number;
  pageSize: number;
}

// Catalog import types
export interface ImportRow {
  year: number;
  make: string;
  model: string;
  trim: string;
  engineName: string | null;
  transmissionType: string | null;
}

export interface ImportError {
  row: number;
  error: string;
}

export interface ImportPreviewResult {
  previewId: string;
  toCreate: ImportRow[];
  toUpdate: ImportRow[];
  errors: ImportError[];
  valid: boolean;
}

export interface ImportApplyResult {
  created: number;
  updated: number;
  errors: ImportError[];
}

// Cascade delete result
export interface CascadeDeleteResult {
  deletedMakes: number;
  deletedModels: number;
  deletedYears: number;
  deletedTrims: number;
  deletedEngines: number;
  totalDeleted: number;
}

// Email template types
export interface EmailTemplate {
  id: string;
  templateKey: string;
  name: string;
  description?: string;
  subject: string;
  body: string;
  variables: string[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface UpdateEmailTemplateRequest {
  subject?: string;
  body?: string;
  isActive?: boolean;
}

export interface PreviewTemplateResponse {
  subject: string;
  body: string;
  html: string;
}

// ============================================
// User Management types (subscription tiers)
// ============================================

// Subscription tier enum
export type SubscriptionTier = 'free' | 'pro' | 'enterprise';

// User with admin status for admin views
export interface ManagedUser {
  id: string;
  auth0Sub: string;
  email: string;
  displayName: string | null;
  notificationEmail: string | null;
  subscriptionTier: SubscriptionTier;
  deactivatedAt: string | null;
  deactivatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  isAdmin: boolean;
  adminRole: 'admin' | 'super_admin' | null;
  vehicleCount: number;
}

// List users response with pagination
export interface ListUsersResponse {
  users: ManagedUser[];
  total: number;
  page: number;
  pageSize: number;
}

// Query params for listing users
export interface ListUsersParams {
  page?: number;
  pageSize?: number;
  search?: string;
  tier?: SubscriptionTier;
  status?: 'active' | 'deactivated' | 'all';
  sortBy?: 'email' | 'createdAt' | 'displayName' | 'subscriptionTier' | 'vehicleCount';
  sortOrder?: 'asc' | 'desc';
}

// Request to update subscription tier
export interface UpdateUserTierRequest {
  subscriptionTier: SubscriptionTier;
}

// Request to deactivate a user
export interface DeactivateUserRequest {
  reason?: string;
}

// Request to update user profile (admin edit)
export interface UpdateUserProfileRequest {
  email?: string;
  displayName?: string;
}

// Request to promote user to admin
export interface PromoteToAdminRequest {
  role?: 'admin' | 'super_admin';
}

// ============================================
// Backup & Restore types
// ============================================

// Backup types
export type BackupFrequency = 'hourly' | 'daily' | 'weekly' | 'monthly';
export type BackupType = 'scheduled' | 'manual';
export type BackupStatus = 'in_progress' | 'completed' | 'failed';
export type BackupCategory = 'hourly' | 'daily' | 'weekly' | 'monthly';

export interface BackupHistory {
  id: string;
  scheduleId: string | null;
  backupType: BackupType;
  filename: string;
  filePath: string;
  fileSizeBytes: number;
  databaseTablesCount: number | null;
  documentsCount: number | null;
  status: BackupStatus;
  errorMessage: string | null;
  startedAt: string;
  completedAt: string | null;
  createdBy: string | null;
  metadata: Record<string, unknown>;
  categories: BackupCategory[];
  expiresAt: string | null;
}

export interface BackupSchedule {
  id: string;
  name: string;
  frequency: BackupFrequency;
  cronExpression: string;
  retentionCount: number;
  isEnabled: boolean;
  lastRunAt: string | null;
  nextRunAt: string | null;
  createdAt: string;
  updatedAt: string;
  lastBackup?: BackupHistory | null;
}

export interface BackupSettings {
  emailOnSuccess: boolean;
  emailOnFailure: boolean;
  adminEmail: string;
  maxBackupSizeMb: number;
  compressionEnabled: boolean;
}

export interface ListBackupsResponse {
  items: BackupHistory[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface CreateBackupRequest {
  name?: string;
  includeDocuments?: boolean;
}

export interface CreateScheduleRequest {
  name: string;
  frequency: BackupFrequency;
  retentionCount?: number;
  isEnabled?: boolean;
}

export interface UpdateScheduleRequest {
  name?: string;
  frequency?: BackupFrequency;
  retentionCount?: number;
  isEnabled?: boolean;
}

export interface RestorePreviewResponse {
  backupId: string;
  manifest: {
    version: string;
    createdAt: string;
    contents: {
      database: { tablesCount: number; sizeBytes: number };
      documents: { totalFiles: number; totalSizeBytes: number };
    };
  };
  warnings: string[];
  estimatedDuration: string;
}

export interface ExecuteRestoreRequest {
  createSafetyBackup?: boolean;
}

// ============================================
// Unified Audit Log types (new centralized audit system)
// ============================================

export type AuditLogCategory = 'auth' | 'vehicle' | 'user' | 'system' | 'admin';
export type AuditLogSeverity = 'info' | 'warning' | 'error';

export interface UnifiedAuditLog {
  id: string;
  category: AuditLogCategory;
  severity: AuditLogSeverity;
  userId: string | null;
  userEmail: string | null;
  action: string;
  resourceType: string | null;
  resourceId: string | null;
  details: Record<string, unknown> | null;
  createdAt: string;
}

export interface UnifiedAuditLogsResponse {
  logs: UnifiedAuditLog[];
  total: number;
  limit: number;
  offset: number;
}

export interface AuditLogFilters {
  search?: string;
  category?: AuditLogCategory;
  severity?: AuditLogSeverity;
  startDate?: string;
  endDate?: string;
  limit?: number;
  offset?: number;
}
