/*
 * M18 관리자 CRUD(사용자·역할/권한·공통코드·메뉴) 실배선 API 계약.
 * 공용 클라이언트(../../api/client)만 사용 — client.ts·endpoints.ts·types.ts 무수정.
 * 정본: 백엔드 컨트롤러 시그니처(com.zioinfo.kintex.system.*).
 *   - 사용자  /api/admin/users        (SysUserController)         — 목록 PageResponse
 *   - 역할    /api/admin/roles         (RoleController)            — 목록·권한·저장·삭제
 *   - 공통코드 /api/common/code-groups·/api/admin/codes/** (CommonCodeController)
 *   - 메뉴    /api/admin/menus         (MenuController)            — flat 목록·저장·삭제
 * ★ 보안: 비밀번호·OTP 시크릿은 조회 DTO에 미포함(백엔드 SysUserDto). 비밀번호는 생성/재설정 시 전송만 하고
 *   화면·목록에는 절대 표시하지 않는다(응답에도 없음).
 */
import { api } from '../../api/client';
import type { PageResponse } from '../../api/types';

// ══════════ 사용자 관리 (SysUserController) ══════════
/** 시스템 사용자 카드 — 민감정보(해시·OTP 시크릿) 미포함. */
export interface SysUser {
  userId: string;
  email: string | null;
  displayName: string | null;
  hallManager: boolean;
  roleCode: string | null;
  deptId: string | null;
  status: string | null;
  otpEnabled: boolean;
  lastLoginAt: string | null;
}

/** 생성/수정 요청. password 는 생성 시에만(응답·목록 노출 금지). */
export interface UserSaveBody {
  email: string;
  displayName: string;
  password?: string;
  roleCode?: string;
  deptId?: string | null;
  hallManager?: boolean;
}

export interface UserSearchParams {
  keyword?: string;
  status?: string;
  roleCode?: string;
  page?: number;
  size?: number;
}

export const sysUserApi = {
  list: (p: UserSearchParams = {}) => {
    const qs = new URLSearchParams();
    if (p.keyword) qs.set('keyword', p.keyword);
    if (p.status) qs.set('status', p.status);
    if (p.roleCode) qs.set('roleCode', p.roleCode);
    qs.set('page', String(p.page ?? 0));
    qs.set('size', String(p.size ?? 20));
    return api.get<PageResponse<SysUser>>(`/api/admin/users?${qs.toString()}`);
  },
  create: (body: UserSaveBody) => api.post<SysUser>('/api/admin/users', body),
  update: (userId: string, body: UserSaveBody) =>
    api.put<SysUser>(`/api/admin/users/${encodeURIComponent(userId)}`, body),
  changeStatus: (userId: string, value: string) =>
    api.patch<void>(`/api/admin/users/${encodeURIComponent(userId)}/status?value=${encodeURIComponent(value)}`),
  resetPassword: (userId: string, newPassword: string) =>
    api.post<void>(`/api/admin/users/${encodeURIComponent(userId)}/password`, { newPassword }),
  resetOtp: (userId: string) =>
    api.post<void>(`/api/admin/users/${encodeURIComponent(userId)}/otp/reset`),
};

export const USER_ROLE_CODES = ['USER', 'MANAGER', 'ADMIN'] as const;
export const USER_STATUSES = ['ACTIVE', 'LOCKED', 'DISABLED'] as const;

// ══════════ 역할/권한 (RoleController) ══════════
export interface Role {
  roleCode: string;
  roleName: string;
  description: string | null;
  useYn: string | null;
  permissions: string[];
}
export interface Permission {
  permCode: string;
  permName: string;
  description: string | null;
}

export const roleApi = {
  list: () => api.get<Role[]>('/api/admin/roles'),
  permissions: () => api.get<Permission[]>('/api/admin/roles/permissions'),
  save: (role: Role) => api.post<void>('/api/admin/roles', role),
  remove: (roleCode: string) => api.del<void>(`/api/admin/roles/${encodeURIComponent(roleCode)}`),
};

// ══════════ 공통코드 (CommonCodeController) ══════════
export interface CodeGroup {
  grpCode: string;
  grpName: string;
  description: string | null;
  useYn: string | null;
  sortOrder: number;
}
export interface Code {
  grpCode: string;
  code: string;
  codeName: string;
  codeValue: string | null;
  sortOrder: number;
  useYn: string | null;
  attr1: string | null;
}

export const codeApi = {
  groups: () => api.get<CodeGroup[]>('/api/common/code-groups'),
  codes: (grpCode: string) => api.get<Code[]>(`/api/common/codes/${encodeURIComponent(grpCode)}`),
  saveGroup: (group: CodeGroup) => api.post<void>('/api/admin/codes/groups', group),
  removeGroup: (grpCode: string) =>
    api.del<void>(`/api/admin/codes/groups/${encodeURIComponent(grpCode)}`),
  saveCode: (code: Code) => api.post<void>('/api/admin/codes', code),
  removeCode: (grpCode: string, code: string) =>
    api.del<void>(`/api/admin/codes/${encodeURIComponent(grpCode)}/${encodeURIComponent(code)}`),
};

// ══════════ 메뉴 (MenuController) ══════════
export interface MenuNode {
  id: string;
  parentId: string | null;
  menuName: string;
  menuPath: string | null;
  icon: string | null;
  prgType: string | null;
  requiredRole: string | null;
  sortOrder: number;
  useYn: string | null;
  children?: MenuNode[];
}

/** 저장 요청(트리 없는 평면 노드). id 가 있으면 수정, 없으면 신규(백엔드 upsert). */
export interface MenuSaveBody {
  id?: string | null;
  parentId?: string | null;
  menuName: string;
  menuPath?: string | null;
  icon?: string | null;
  prgType?: string | null;
  requiredRole?: string | null;
  sortOrder?: number | null;
  useYn?: string | null;
}

export const menuApi = {
  all: () => api.get<MenuNode[]>('/api/admin/menus'),
  save: (body: MenuSaveBody) => api.post<void>('/api/admin/menus', body),
  remove: (id: string) => api.del<void>(`/api/admin/menus/${encodeURIComponent(id)}`),
};

export const MENU_PRG_TYPES = ['GROUP', 'SCREEN', 'LINK'] as const;

// ══════════ 테넌트 (TenantAdminController · 플랫폼 슈퍼관리자) ══════════
/** 관리자 테넌트 목록 행 — 백엔드 TenantAdminDto 와 정합(code=tenant_id 불변 코드). */
export interface Tenant {
  code: string;
  name: string;
  domain: string | null;
  status: string; // 'active' | 'onboarding' | 'suspended'
  events: number;
  users: number;
  createdAt: string | null;
}
/** 테넌트 등록(온보딩 1단계) 요청 — 백엔드 TenantCreateRequest. status 생략 시 서버가 'onboarding'. */
export interface TenantCreateBody {
  code: string;
  name: string;
  domain?: string | null;
  status?: string;
}

export const tenantApi = {
  list: () => api.get<Tenant[]>('/api/admin/tenants'),
  create: (body: TenantCreateBody) => api.post<Tenant>('/api/admin/tenants', body),
};

export const TENANT_STATUSES = ['onboarding', 'active', 'suspended'] as const;
