'use server';

import { createCrudService, type ActionResult } from '@/lib/api/create-crud-service';
import type { Rank } from './types';

// ===== API 응답 타입 =====
interface PositionApiData {
  id: number;
  tenant_id: number;
  type: 'rank' | 'title';
  name: string;
  sort_order: number;
  is_active: boolean;
  created_at?: string;
  updated_at?: string;
}

// ===== CRUD 서비스 생성 =====
const rankService = createCrudService<PositionApiData, Rank>({
  basePath: '/api/v1/positions',
  transform: (api) => ({
    id: api.id,
    name: api.name,
    order: api.sort_order,
    isActive: api.is_active,
    createdAt: api.created_at,
    updatedAt: api.updated_at,
  }),
  entityName: '직급',
  defaultQueryParams: { type: 'rank' },
  defaultCreateBody: { type: 'rank' },
});

// ===== Server Action 래퍼 =====
// Next.js Server Action은 'use server' 파일에서 직접 선언된 async function만 인식
// 팩토리 반환 함수를 직접 export하면 Server Action으로 인식 안 될 수 있음

export async function getRanks(params?: {
  is_active?: boolean;
  q?: string;
}): Promise<ActionResult<Rank[]>> {
  return rankService.getList(params);
}

export async function createRank(data: {
  name: string;
  sort_order?: number;
  is_active?: boolean;
}): Promise<ActionResult<Rank>> {
  return rankService.create({
    name: data.name,
    sort_order: data.sort_order,
    is_active: data.is_active ?? true,
  });
}

export async function updateRank(
  id: number,
  data: {
    name?: string;
    sort_order?: number;
    is_active?: boolean;
  }
): Promise<ActionResult<Rank>> {
  return rankService.update(id, data);
}

export async function deleteRank(id: number): Promise<ActionResult> {
  return rankService.remove(id);
}

export async function reorderRanks(
  items: { id: number; sort_order: number }[]
): Promise<ActionResult> {
  return rankService.reorder(items);
}
