/**
 * Enterprise IdP types for SmartAuth Phase 6A.
 * Supports SAML 2.0 and OIDC federation per organization.
 */

import { z } from 'zod';

export interface EnterpriseIdpDoc {
  id: string; // "idp_{orgId}_{protocol}"
  orgId: string;
  productId: string;
  protocol: 'saml' | 'oidc';
  name: string;
  /** Email domains that auto-link to this IdP (e.g. ["acme.com"]) */
  emailDomains: string[];
  enabled: boolean;
  /** SAML-specific config */
  saml?: {
    entityId: string;
    ssoUrl: string;
    certificate: string; // X.509 PEM
    signatureAlgorithm?: string;
    digestAlgorithm?: string;
  };
  /** OIDC-specific config */
  oidc?: {
    issuer: string;
    clientId: string;
    clientSecret: string;
    authorizationUrl: string;
    tokenUrl: string;
    userinfoUrl?: string;
    scopes: string[];
  };
  createdAt: string;
  updatedAt: string;
}

export const CreateIdpSchema = z.object({
  orgId: z.string().min(1),
  protocol: z.enum(['saml', 'oidc']),
  name: z.string().min(1).max(100),
  emailDomains: z.array(z.string().min(3)).min(1),
  enabled: z.boolean().default(true),
  saml: z
    .object({
      entityId: z.string().min(1),
      ssoUrl: z.string().url(),
      certificate: z.string().min(1),
      signatureAlgorithm: z.string().optional(),
      digestAlgorithm: z.string().optional(),
    })
    .optional(),
  oidc: z
    .object({
      issuer: z.string().url(),
      clientId: z.string().min(1),
      clientSecret: z.string().min(1),
      authorizationUrl: z.string().url(),
      tokenUrl: z.string().url(),
      userinfoUrl: z.string().url().optional(),
      scopes: z.array(z.string()).default(['openid', 'email', 'profile']),
    })
    .optional(),
});

export const UpdateIdpSchema = CreateIdpSchema.partial().omit({ orgId: true, protocol: true });

export const SamlCallbackSchema = z.object({
  SAMLResponse: z.string().min(1),
  RelayState: z.string().optional(),
});

export const OidcCallbackSchema = z.object({
  code: z.string().min(1),
  state: z.string().min(1),
});
