import type { TaskFormData } from './taskFormState';
import type { RoutineCategory } from './routineCategories';
import { displayFlagsForTaskType } from './taskType';
import { serializeIssueEntries } from './taskIssues';

function basePayload(data: TaskFormData, taskType: string): Record<string, unknown> {
  const flags = displayFlagsForTaskType(taskType);
  const issueEntries = serializeIssueEntries(data.issueEntries);
  return {
    title: data.title,
    section: data.section || null,
    tag: data.tag || null,
    taskType,
    status: data.status,
    progress: data.progress,
    description: data.description || null,
    issueEntries,
    startDate: data.startDate || null,
    dueDate: data.dueDate || null,
    showDate: flags.showDate,
    showDescription: flags.showDescription,
    showStatus: flags.showStatus,
    showIssue: flags.showIssue,
    showProgress: flags.showProgress,
    quarter: data.quarter,
    pmMemberId: data.pmMemberId || null,
    assigneeMemberIds: data.assigneeMemberIds,
  };
}

/** @deprecated variant별 helper 사용 권장 */
export function taskFormToApiPayload(data: TaskFormData): Record<string, unknown> {
  return basePayload(data, data.taskType || '실행과제');
}

export function projectFormToApiPayload(data: TaskFormData): Record<string, unknown> {
  return {
    ...basePayload(data, '실행과제'),
    detailDescription: data.detailDescription || null,
  };
}

export function routineFormToApiPayload(data: TaskFormData): Record<string, unknown> {
  return {
    ...basePayload(data, '기반업무'),
    category: data.category || null,
    section: null,
  };
}

/** 상시업무 대분류 탭용 — 카테고리별 대표 task 자동 생성 */
export function routineCategoryShellPayload(
  category: RoutineCategory,
  quarter: string,
): Record<string, unknown> {
  const flags = displayFlagsForTaskType('기반업무');
  return {
    title: category,
    category,
    section: null,
    taskType: '기반업무',
    quarter,
    status: 'IN_PROGRESS',
    progress: 0,
    description: null,
    issueEntries: [],
    assigneeMemberIds: [],
    pmMemberId: null,
    startDate: null,
    dueDate: null,
    ...flags,
  };
}
