import { z } from 'zod';

// Base provider configuration
export const baseProviderConfigSchema = z.object({
  name: z.string(),
  enabled: z.boolean().default(true),
  priority: z.number().default(0),
  timeout: z.number().default(30000),
  retries: z.number().default(3),
});

// EOD Historical Data provider
export const eodProviderConfigSchema = baseProviderConfigSchema.extend({
  apiKey: z.string(),
  baseUrl: z.string().default('https://eodhistoricaldata.com/api'),
  tier: z.enum(['free', 'fundamentals', 'all-in-one']).default('free'),
});

// Interactive Brokers provider
export const ibProviderConfigSchema = baseProviderConfigSchema.extend({
  gateway: z
    .object({
      host: z.string().default('localhost'),
      port: z.number().default(5000),
      clientId: z.number().default(1),
    })
    .default({
      host: 'localhost',
      port: 5000,
      clientId: 1,
    }),
  account: z.string().optional(),
  marketDataType: z
    .union([
      z.enum(['live', 'delayed', 'frozen']),
      z.enum(['1', '2', '3']).transform(val => {
        const mapping = { '1': 'live', '2': 'frozen', '3': 'delayed' } as const;
        return mapping[val];
      }),
    ])
    .default('delayed'),
});

// QuoteMedia provider
export const qmProviderConfigSchema = baseProviderConfigSchema.extend({
  username: z.string(),
  password: z.string(),
  baseUrl: z.string().default('https://app.quotemedia.com/quotetools'),
  webmasterId: z.string(),
});

// Yahoo Finance provider
export const yahooProviderConfigSchema = baseProviderConfigSchema.extend({
  baseUrl: z.string().default('https://query1.finance.yahoo.com'),
  cookieJar: z.boolean().default(true),
  crumb: z.string().optional(),
});

// WebShare proxy provider
export const webshareProviderConfigSchema = z.object({
  apiKey: z.string().optional(),
  apiUrl: z.string().default('https://proxy.webshare.io/api/v2/'),
  enabled: z.boolean().default(true),
});

// Combined provider configuration
export const providerConfigSchema = z.object({
  eod: eodProviderConfigSchema.optional(),
  ib: ibProviderConfigSchema.optional(),
  qm: qmProviderConfigSchema.optional(),
  yahoo: yahooProviderConfigSchema.optional(),
  webshare: webshareProviderConfigSchema.optional(),
});

// Dynamic provider configuration type
export type ProviderName = 'eod' | 'ib' | 'qm' | 'yahoo' | 'webshare';

export const providerSchemas = {
  eod: eodProviderConfigSchema,
  ib: ibProviderConfigSchema,
  qm: qmProviderConfigSchema,
  yahoo: yahooProviderConfigSchema,
  webshare: webshareProviderConfigSchema,
} as const;
