import { z } from 'zod';

// ==========================================
// SYSTEM OVERVIEW SCHEMAS
// ==========================================

export const SystemHealthStatusSchema = z.object({
  healthy: z.boolean(),
  service: z.string(),
  latency: z.number().optional(),
  error: z.string().optional(),
});

export const SystemOverviewSchema = z.object({
  version: z.string(),
  commit: z.string().optional(),
  uptime: z.number(), // seconds
  deployedAt: z.string().datetime().optional(),
  database: SystemHealthStatusSchema,
  redis: SystemHealthStatusSchema,
  rateLimiter: z.object({
    mode: z.enum(['fail-open', 'fail-closed']),
    healthy: z.boolean(),
    error: z.string().optional(),
  }),
  lighthouseScores: z
    .object({
      performance: z.number().min(0).max(100).optional(),
      accessibility: z.number().min(0).max(100).optional(),
      bestPractices: z.number().min(0).max(100).optional(),
      seo: z.number().min(0).max(100).optional(),
      lastRun: z.string().datetime().optional(),
    })
    .optional(),
});

export type SystemOverview = z.infer<typeof SystemOverviewSchema>;
export type SystemHealthStatus = z.infer<typeof SystemHealthStatusSchema>;

// ==========================================
// USER LOOKUP SCHEMAS
// ==========================================

export const UserLookupQuerySchema = z.object({
  query: z.string().min(1).max(255),
  queryType: z.enum(['email', 'phone', 'id']).optional(),
});

export const UserLookupResultSchema = z.object({
  id: z.string(),
  email: z.string().email(),
  phone: z.string().nullable(),
  name: z.string().nullable(),
  subscriptionTier: z.string().nullable(),
  subscriptionStatus: z.string().nullable(),
  trialEndsAt: z.string().datetime().nullable(),
  createdAt: z.string().datetime(),
  lastLoginAt: z.string().datetime().nullable(),
  isActive: z.boolean(),
  featureFlags: z.record(z.boolean()).optional(),
  recentSessions: z
    .array(
      z.object({
        id: z.string(),
        createdAt: z.string().datetime(),
        ipAddress: z.string().nullable(),
        userAgent: z.string().nullable(),
      })
    )
    .optional(),
  supportNotes: z
    .array(
      z.object({
        id: z.string(),
        note: z.string(),
        createdAt: z.string().datetime(),
        createdBy: z.string(),
      })
    )
    .optional(),
});

export type UserLookupQuery = z.infer<typeof UserLookupQuerySchema>;
export type UserLookupResult = z.infer<typeof UserLookupResultSchema>;

// ==========================================
// RECENT ERRORS SCHEMAS
// ==========================================

export const ErrorFilterSchema = z.object({
  timeWindow: z.enum(['1h', '6h', '24h', '7d']).default('24h'),
  severity: z.enum(['low', 'medium', 'high', 'critical']).optional(),
  route: z.string().optional(),
  limit: z.number().int().min(1).max(100).default(20),
  offset: z.number().int().min(0).default(0),
});

export const ErrorEntrySchema = z.object({
  id: z.string(),
  timestamp: z.string().datetime(),
  route: z.string(),
  method: z.string(),
  statusCode: z.number().int().optional(),
  errorMessage: z.string(),
  errorType: z.string().optional(),
  userId: z.string().nullable(),
  userEmail: z.string().nullable(), // redacted/masked
  severity: z.enum(['low', 'medium', 'high', 'critical']),
  sentryUrl: z.string().url().optional(),
  stackTrace: z.string().optional(), // truncated for UI
});

export const ErrorsResponseSchema = z.object({
  errors: z.array(ErrorEntrySchema),
  total: z.number().int(),
  hasMore: z.boolean(),
});

export type ErrorFilter = z.infer<typeof ErrorFilterSchema>;
export type ErrorEntry = z.infer<typeof ErrorEntrySchema>;
export type ErrorsResponse = z.infer<typeof ErrorsResponseSchema>;

// ==========================================
// BACKGROUND JOBS SCHEMAS
// ==========================================

export const JobQueueStatusSchema = z.object({
  queueName: z.string(),
  status: z.enum(['healthy', 'degraded', 'failing']),
  activeJobs: z.number().int().min(0),
  waitingJobs: z.number().int().min(0),
  failedJobs: z.number().int().min(0),
  completedJobs: z.number().int().min(0),
  oldestJobAge: z.number().int().nullable(), // seconds
  lastProcessedAt: z.string().datetime().nullable(),
  lastFailure: z
    .object({
      timestamp: z.string().datetime(),
      error: z.string(),
      jobId: z.string(),
    })
    .nullable(),
});

export const CronJobStatusSchema = z.object({
  jobName: z.string(),
  schedule: z.string(), // cron expression
  lastRun: z.string().datetime().nullable(),
  nextRun: z.string().datetime().nullable(),
  lastStatus: z.enum(['success', 'failed', 'running', 'pending']),
  lastDuration: z.number().int().nullable(), // milliseconds
  lastError: z.string().nullable(),
});

export const BackgroundJobsResponseSchema = z.object({
  queues: z.array(JobQueueStatusSchema),
  cronJobs: z.array(CronJobStatusSchema),
  overall: z.object({
    healthy: z.boolean(),
    totalActive: z.number().int(),
    totalFailed: z.number().int(),
  }),
});

export type JobQueueStatus = z.infer<typeof JobQueueStatusSchema>;
export type CronJobStatus = z.infer<typeof CronJobStatusSchema>;
export type BackgroundJobsResponse = z.infer<typeof BackgroundJobsResponseSchema>;

// ==========================================
// AUDIT LOG SCHEMAS
// ==========================================

export const StaffAuditLogSchema = z.object({
  staffUserId: z.string(),
  staffEmail: z.string(),
  action: z.enum(['user_lookup', 'view_errors', 'view_jobs', 'view_system']),
  targetUserId: z.string().nullable(),
  targetUserEmail: z.string().nullable(),
  metadata: z.record(z.unknown()).optional(),
  timestamp: z.string().datetime(),
  ipAddress: z.string().nullable(),
});

export type StaffAuditLog = z.infer<typeof StaffAuditLogSchema>;
