'use server';

import { createCrudService, type ActionResult } from '@/lib/api/create-crud-service';
import type { Title } 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 titleService = createCrudService<PositionApiData, Title>({
  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: 'title' },
  defaultCreateBody: { type: 'title' },
});

// ===== Server Action 래퍼 =====

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

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

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

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

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