'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { AccountSubject, AccountSubjectApiData } from './types';
import { transformAccountSubjectApi } from './types';

// ===== 계정과목 목록 조회 =====
export async function getAccountSubjects(params?: {
  search?: string;
  category?: string;
  subCategory?: string;
  departmentType?: string;
  depth?: number;
  isActive?: boolean;
  selectable?: boolean;
}): Promise<ActionResult<AccountSubject[]>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/account-subjects', {
      search: params?.search || undefined,
      category: params?.category && params.category !== 'all' ? params.category : undefined,
      sub_category: params?.subCategory || undefined,
      department_type: params?.departmentType || undefined,
      depth: params?.depth,
      is_active: params?.isActive,
      selectable: params?.selectable,
    }),
    transform: (data: AccountSubjectApiData[]) => data.map(transformAccountSubjectApi),
    errorMessage: '계정과목 목록 조회에 실패했습니다.',
  });
}

// ===== 계정과목 추가 =====
export async function createAccountSubject(data: {
  code: string;
  name: string;
  category: string;
  subCategory?: string;
  parentCode?: string;
  depth?: number;
  departmentType?: string;
  description?: string;
  sortOrder?: number;
}): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/account-subjects'),
    method: 'POST',
    body: {
      code: data.code,
      name: data.name,
      category: data.category,
      sub_category: data.subCategory || undefined,
      parent_code: data.parentCode || undefined,
      depth: data.depth ?? 3,
      department_type: data.departmentType || 'common',
      description: data.description || undefined,
      sort_order: data.sortOrder,
    },
    errorMessage: '계정과목 추가에 실패했습니다.',
  });
}

// ===== 계정과목 수정 =====
export async function updateAccountSubject(
  id: string,
  data: {
    name?: string;
    category?: string;
    subCategory?: string;
    parentCode?: string;
    depth?: number;
    departmentType?: string;
    description?: string;
    sortOrder?: number;
  }
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/account-subjects/${id}`),
    method: 'PUT',
    body: {
      name: data.name,
      category: data.category,
      sub_category: data.subCategory,
      parent_code: data.parentCode,
      depth: data.depth,
      department_type: data.departmentType,
      description: data.description,
      sort_order: data.sortOrder,
    },
    errorMessage: '계정과목 수정에 실패했습니다.',
  });
}

// ===== 계정과목 상태 토글 =====
export async function updateAccountSubjectStatus(
  id: string,
  isActive: boolean
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/account-subjects/${id}/status`),
    method: 'PATCH',
    body: { is_active: isActive },
    errorMessage: '계정과목 상태 변경에 실패했습니다.',
  });
}

// ===== 계정과목 삭제 =====
export async function deleteAccountSubject(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/account-subjects/${id}`),
    method: 'DELETE',
    errorMessage: '계정과목 삭제에 실패했습니다.',
  });
}

// ===== 기본 계정과목표 일괄 생성 =====
export async function seedDefaultAccountSubjects(): Promise<ActionResult<{ inserted_count: number }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/account-subjects/seed-defaults'),
    method: 'POST',
    errorMessage: '기본 계정과목 생성에 실패했습니다.',
  });
}
