/*
 * W12 시스템관리 기본기(1차) 실배선 API 계약. 공용 클라이언트(../../api/client)만 사용
 * — client.ts·endpoints.ts·types.ts 무수정.
 * 정본: 백엔드 컨트롤러 시그니처(com.zioinfo.kintex.system.*, V37 스키마).
 *   조직    /api/admin/depts (트리) · /api/admin/companies (PageResponse)
 *   프로그램 /api/admin/programs
 *   역할-메뉴 /api/admin/roles/{roleCode}/menus
 *   인증정책 /api/admin/auth-policy
 *   로그인이력 /api/admin/login-history (PageResponse, 읽기전용)
 *   오류로그  /api/admin/error-log (PageResponse, 읽기전용)
 *   시스템상태 /api/admin/system-health
 *   메일/알림 /api/admin/mail-config · /api/admin/notify-config
 * ★ 보안: 연락처(회사)·이메일/IP(로그인이력)는 백엔드에서 마스킹되어 도착한다.
 *   시크릿 설정(mail.password 등)은 secretYn='Y'로 마스킹(********) 도착 — 미변경 시 저장 전송 제외.
 */
import { api } from '../../api/client';
import type { PageResponse } from '../../api/types';

// ══════════ 1. 조직 — 부서 트리 ══════════
export interface DeptNode {
  id: string;
  deptName: string;
  parentId: string | null;
  sortOrder: number;
  useYn: string | null;
  children?: DeptNode[];
}
export interface DeptSaveBody {
  id?: string | null;
  deptName: string;
  parentId?: string | null;
  sortOrder?: number | null;
  useYn?: string | null;
}
export const deptApi = {
  tree: () => api.get<DeptNode[]>('/api/admin/depts'),
  save: (body: DeptSaveBody) => api.post<void>('/api/admin/depts', body),
  remove: (id: string) => api.del<void>(`/api/admin/depts/${encodeURIComponent(id)}`),
};

// ══════════ 1. 조직 — 회사(거래처) ══════════
export interface Company {
  id: string;
  companyName: string;
  bizNo: string | null;
  ceoName: string | null;
  bizType: string | null;
  contactName: string | null;
  contactTel: string | null; // 마스킹됨
  address: string | null;
  partnerType: string | null;
  useYn: string | null;
}
export interface CompanySaveBody {
  id?: string | null;
  companyName: string;
  bizNo?: string | null;
  ceoName?: string | null;
  bizType?: string | null;
  contactName?: string | null;
  contactTel?: string | null;
  address?: string | null;
  partnerType?: string | null;
  useYn?: string | null;
}
export interface CompanySearchParams {
  keyword?: string;
  partnerType?: string;
  page?: number;
  size?: number;
}
export const companyApi = {
  list: (p: CompanySearchParams = {}) => {
    const qs = new URLSearchParams();
    if (p.keyword) qs.set('keyword', p.keyword);
    if (p.partnerType) qs.set('partnerType', p.partnerType);
    qs.set('page', String(p.page ?? 0));
    qs.set('size', String(p.size ?? 20));
    return api.get<PageResponse<Company>>(`/api/admin/companies?${qs.toString()}`);
  },
  save: (body: CompanySaveBody) => api.post<void>('/api/admin/companies', body),
  remove: (id: string) => api.del<void>(`/api/admin/companies/${encodeURIComponent(id)}`),
};
export const PARTNER_TYPES = ['CONTRACTOR', 'SUPPLIER', 'AGENCY', 'ETC'] as const;

// ══════════ 2. 프로그램(화면) ══════════
export interface Program {
  id: string;
  programName: string;
  programType: string | null;
  programUrl: string | null;
  category: string | null;
  useYn: string | null;
}
export interface ProgramSaveBody {
  id?: string | null;
  programName: string;
  programType?: string | null;
  programUrl?: string | null;
  category?: string | null;
  useYn?: string | null;
}
export const programApi = {
  list: (keyword?: string, category?: string) => {
    const qs = new URLSearchParams();
    if (keyword) qs.set('keyword', keyword);
    if (category) qs.set('category', category);
    const s = qs.toString();
    return api.get<Program[]>(`/api/admin/programs${s ? `?${s}` : ''}`);
  },
  save: (body: ProgramSaveBody) => api.post<void>('/api/admin/programs', body),
  remove: (id: string) => api.del<void>(`/api/admin/programs/${encodeURIComponent(id)}`),
};
export const PROGRAM_TYPES = ['SCREEN', 'POPUP', 'LINK'] as const;

// ══════════ 3. 역할-메뉴 매핑 ══════════
export interface RoleMenu {
  menuId: string;
  menuName: string;
  parentId: string | null;
  sortOrder: number;
  mapped: boolean;
  readYn: string;
  writeYn: string;
}
export interface RoleMenuSaveBody {
  menus: { menuId: string; readYn: string; writeYn: string }[];
}
export const roleMenuApi = {
  list: (roleCode: string) =>
    api.get<RoleMenu[]>(`/api/admin/roles/${encodeURIComponent(roleCode)}/menus`),
  save: (roleCode: string, body: RoleMenuSaveBody) =>
    api.post<void>(`/api/admin/roles/${encodeURIComponent(roleCode)}/menus`, body),
};

// ══════════ 4. 인증 정책 ══════════
export interface AuthPolicy {
  pwMinLength: number;
  pwRequireUpper: string;
  pwRequireNumber: string;
  pwRequireSpecial: string;
  pwExpireDays: number;
  loginMaxFail: number;
  lockMinutes: number;
  sessionTimeoutMin: number;
  updatedAt: string | null;
  updatedBy: string | null;
}
export type AuthPolicySaveBody = Omit<AuthPolicy, 'updatedAt' | 'updatedBy'>;
export const authPolicyApi = {
  get: () => api.get<AuthPolicy>('/api/admin/auth-policy'),
  save: (body: AuthPolicySaveBody) => api.put<void>('/api/admin/auth-policy', body),
};

// ══════════ 5. 로그인 이력(읽기전용) ══════════
export interface LoginHistoryRow {
  id: number;
  userId: string | null;
  emailMasked: string | null;
  result: string | null;
  failReason: string | null;
  ipMasked: string | null;
  userAgent: string | null;
  createdAt: string | null;
}
export const loginHistoryApi = {
  list: (result: string, userId: string, page: number, size: number) => {
    const qs = new URLSearchParams();
    if (result) qs.set('result', result);
    if (userId) qs.set('userId', userId);
    qs.set('page', String(page));
    qs.set('size', String(size));
    return api.get<PageResponse<LoginHistoryRow>>(`/api/admin/login-history?${qs.toString()}`);
  },
};

// ══════════ 6. 오류 로그(읽기전용) ══════════
export interface ErrorLogRow {
  id: number;
  errorCode: string | null;
  summary: string | null;
  path: string | null;
  method: string | null;
  actorId: string | null;
  createdAt: string | null;
}
export const errorLogApi = {
  list: (errorCode: string, page: number, size: number) => {
    const qs = new URLSearchParams();
    if (errorCode) qs.set('errorCode', errorCode);
    qs.set('page', String(page));
    qs.set('size', String(size));
    return api.get<PageResponse<ErrorLogRow>>(`/api/admin/error-log?${qs.toString()}`);
  },
};

// ══════════ 7. 시스템 상태 ══════════
export interface SystemHealth {
  db: string;
  redis: string;
  worker: string;
  queueDepth: number;
  diskFreePct: number;
  diskFreeMb: number;
  memUsedPct: number;
  uptimeSec: number;
  version: string;
  time: string;
}
export const systemHealthApi = {
  get: () => api.get<SystemHealth>('/api/admin/system-health'),
};

// ══════════ 8. 메일/알림 설정 ══════════
export interface InfraConfigRow {
  settingKey: string;
  settingValue: string | null;
  valueType: string | null;
  description: string | null;
  secretYn: string | null;
}
export interface InfraConfigUpdateBody {
  items: { settingKey: string; settingValue: string | null }[];
}
export const CONFIG_MASK = '********';
export const mailConfigApi = {
  list: () => api.get<InfraConfigRow[]>('/api/admin/mail-config'),
  save: (body: InfraConfigUpdateBody) => api.put<void>('/api/admin/mail-config', body),
};
export const notifyConfigApi = {
  list: () => api.get<InfraConfigRow[]>('/api/admin/notify-config'),
  save: (body: InfraConfigUpdateBody) => api.put<void>('/api/admin/notify-config', body),
};
