/**
 * 플로우 전용 외부 DB 연동 타입 정의
 * (기존 제어관리 외부 DB와 별도)
 */

// ==================== 연동 타입 ====================

export type FlowIntegrationType = "internal" | "external_db" | "procedure" | "rest_api" | "webhook" | "hybrid";

// ==================== 외부 DB 연결 ====================

export interface FlowExternalDbConnection {
  id: number;
  name: string;
  description?: string;
  dbType: "postgresql" | "mysql" | "mssql" | "oracle";
  host: string;
  port: number;
  databaseName: string;
  username: string;
  passwordEncrypted: string; // 암호화된 비밀번호 (화면에는 표시하지 않음)
  sslEnabled: boolean;
  connectionOptions?: Record<string, any>;
  isActive: boolean;
  createdBy?: string;
  updatedBy?: string;
  createdAt: string;
  updatedAt: string;
}

export interface CreateFlowExternalDbConnectionRequest {
  name: string;
  description?: string;
  dbType: "postgresql" | "mysql" | "mssql" | "oracle";
  host: string;
  port: number;
  databaseName: string;
  username: string;
  password: string; // 평문 비밀번호 (생성 시에만 사용)
  sslEnabled?: boolean;
  connectionOptions?: Record<string, any>;
}

export interface UpdateFlowExternalDbConnectionRequest {
  name?: string;
  description?: string;
  host?: string;
  port?: number;
  databaseName?: string;
  username?: string;
  password?: string; // 평문 비밀번호 (변경 시에만)
  sslEnabled?: boolean;
  connectionOptions?: Record<string, any>;
  isActive?: boolean;
}

// ==================== 외부 DB 연동 설정 ====================

export interface FlowExternalDbIntegrationConfig {
  type: "external_db";
  connectionId: number; // 연결 ID
  operation: "update" | "insert" | "delete" | "custom";
  tableName: string;
  updateFields?: Record<string, any>; // 업데이트할 필드
  whereCondition?: Record<string, any>; // WHERE 조건
  customQuery?: string; // 커스텀 쿼리
}

// 프로시저 호출 파라미터 정의
export interface FlowProcedureParam {
  name: string;
  dataType: string;
  mode: "IN" | "OUT" | "INOUT";
  source: "record_field" | "static" | "step_variable";
  field?: string;
  value?: string;
}

// 프로시저 호출 설정
export interface FlowProcedureConfig {
  type: "procedure";
  dbSource: "internal" | "external";
  connectionId?: number;
  procedureName: string;
  procedureSchema?: string;
  callType: "procedure" | "function";
  parameters: FlowProcedureParam[];
}

// 프로시저/함수 목록 항목
export interface ProcedureListItem {
  name: string;
  schema: string;
  type: "PROCEDURE" | "FUNCTION";
  returnType?: string;
}

// 프로시저 파라미터 정보
export interface ProcedureParameterInfo {
  name: string;
  position: number;
  dataType: string;
  mode: "IN" | "OUT" | "INOUT";
  defaultValue?: string;
}

// 연동 설정 통합 타입
export type FlowIntegrationConfig =
  | FlowExternalDbIntegrationConfig
  | FlowProcedureConfig;

// ==================== 연동 로그 ====================

export interface FlowIntegrationLog {
  id: number;
  flowDefinitionId: number;
  stepId: number;
  dataId?: string;
  integrationType: string;
  connectionId?: number;
  requestPayload?: Record<string, any>;
  responsePayload?: Record<string, any>;
  status: "success" | "failed" | "timeout" | "rollback";
  errorMessage?: string;
  executionTimeMs?: number;
  executedBy?: string;
  executedAt: string;
}

// ==================== API 응답 ====================

export interface FlowExternalDbConnectionListResponse {
  success: boolean;
  data: FlowExternalDbConnection[];
  message?: string;
}

export interface FlowExternalDbConnectionResponse {
  success: boolean;
  data?: FlowExternalDbConnection;
  message?: string;
  error?: string;
}

export interface FlowExternalDbConnectionTestResponse {
  success: boolean;
  message: string;
}

// ==================== UI 관련 ====================

export const DB_TYPE_OPTIONS = [
  { value: "postgresql", label: "PostgreSQL" },
  { value: "mysql", label: "MySQL" },
  { value: "mssql", label: "MS SQL Server" },
  { value: "oracle", label: "Oracle" },
] as const;

export const OPERATION_OPTIONS = [
  { value: "update", label: "업데이트 (UPDATE)" },
  { value: "insert", label: "삽입 (INSERT)" },
  { value: "delete", label: "삭제 (DELETE)" },
  { value: "custom", label: "커스텀 쿼리" },
] as const;

export const INTEGRATION_TYPE_OPTIONS = [
  { value: "internal", label: "내부 DB (기본)" },
  { value: "external_db", label: "외부 DB 연동" },
  { value: "procedure", label: "프로시저/함수 호출" },
  { value: "rest_api", label: "REST API 연동" },
  { value: "webhook", label: "Webhook (추후 지원)" },
  { value: "hybrid", label: "복합 연동 (추후 지원)" },
] as const;

// ==================== 헬퍼 함수 ====================

export function getDbTypeLabel(dbType: string): string {
  const option = DB_TYPE_OPTIONS.find((opt) => opt.value === dbType);
  return option?.label || dbType;
}

export function getOperationLabel(operation: string): string {
  const option = OPERATION_OPTIONS.find((opt) => opt.value === operation);
  return option?.label || operation;
}

export function getIntegrationTypeLabel(type: string): string {
  const option = INTEGRATION_TYPE_OPTIONS.find((opt) => opt.value === type);
  return option?.label || type;
}
