/*
 * 공통/시스템관리 레이어 API 래퍼 (Phase B §5B) — 2차 인증(OTP)·공통코드·메뉴·알림.
 * 백엔드 계약: /api/auth/otp/**, /api/common/**, /api/work/notifications/**.
 */
import { api } from './client';
import type { LoginResponse, PageResponse } from './types';

// ── 2차 인증(OTP) ──
export interface SecureLoginResponse {
  status: 'OK' | 'OTP_REQUIRED';
  challengeToken: string | null;
  login: LoginResponse | null;
}
export interface OtpSetupResponse {
  secret: string;
  otpAuthUri: string;
  qrImageDataUri: string;
}
export interface OtpStatusResponse {
  otpEnabled: boolean;
  verifyMethod: string;
}

export const twoFactorApi = {
  secureLogin: (email: string, password: string) =>
    api.post<SecureLoginResponse>('/api/auth/login/secure', { email, password }, { anonymous: true }),
  verifyOtp: (challengeToken: string, code: string) =>
    api.post<LoginResponse>('/api/auth/otp/verify', { challengeToken, code }, { anonymous: true }),
  setup: () => api.post<OtpSetupResponse>('/api/auth/otp/setup'),
  confirm: (code: string) => api.post<void>('/api/auth/otp/confirm', { code }),
  status: () => api.get<OtpStatusResponse>('/api/auth/otp/status'),
  resetSelf: () => api.post<void>('/api/auth/otp/reset'),
};

// ── 공통코드·메뉴 ──
export interface CodeGroupDto {
  grpCode: string;
  grpName: string;
  description: string | null;
  useYn: string;
  sortOrder: number;
}
export interface CodeDto {
  grpCode: string;
  code: string;
  codeName: string;
  codeValue: string | null;
  sortOrder: number;
  useYn: string;
  attr1: string | null;
}
export interface MenuDto {
  id: string;
  parentId: string | null;
  menuName: string;
  menuPath: string | null;
  icon: string | null;
  prgType: string;
  requiredRole: string | null;
  sortOrder: number;
  useYn: string;
  children: MenuDto[];
}

export const commonApi = {
  codeGroups: () => api.get<CodeGroupDto[]>('/api/common/code-groups'),
  codes: (grpCode: string) => api.get<CodeDto[]>(`/api/common/codes/${encodeURIComponent(grpCode)}`),
  menus: () => api.get<MenuDto[]>('/api/common/menus'),
};

// ── 알림 ──
export interface NotificationDto {
  id: string;
  recipientId: string;
  eventId: string | null;
  notiType: string;
  title: string;
  message: string | null;
  link: string | null;
  readAt: string | null;
  createdAt: string;
}

export const notificationApi = {
  list: (unreadOnly = false, page = 0, size = 20) =>
    api.get<PageResponse<NotificationDto>>(
      `/api/work/notifications?unreadOnly=${unreadOnly}&page=${page}&size=${size}`,
    ),
  unreadCount: () => api.get<{ unread: number }>('/api/work/notifications/unread-count'),
  read: (id: string) => api.post<void>(`/api/work/notifications/${encodeURIComponent(id)}/read`),
  readAll: () => api.post<void>('/api/work/notifications/read-all'),
};
