import { ElMessageBox } from 'element-plus';

import { $t } from '#/locales';

type ApprovalRequirementApi = {
  get: (
    url: string,
    config: { params: { id: number | string } },
  ) => Promise<{ data?: boolean; errorCode?: number }>;
};

type ConfirmPublishOptions = {
  api: ApprovalRequirementApi;
  confirmMessage: string;
  id: number | string;
  resourcePath: string;
  title: string;
};

export type PublishConfirmation = {
  applicationReason?: string;
};

/**
 * 预检发布审批并完成相应的确认交互。
 *
 * @param options 发布确认参数
 * @returns 用户取消时返回 null，否则返回提交参数
 */
export async function confirmPublishSubmission(
  options: ConfirmPublishOptions,
): Promise<null | PublishConfirmation> {
  const response = await options.api.get(
    `${options.resourcePath}/publishApprovalRequirement`,
    {
      params: { id: options.id },
    },
  );
  try {
    if (!response.data) {
      await ElMessageBox.confirm(options.confirmMessage, options.title, {
        cancelButtonText: $t('button.cancel'),
        confirmButtonText: $t('button.confirm'),
        type: 'info',
      });
      return {};
    }
    const { value } = await ElMessageBox.prompt(
      $t('approval.message.applicationReasonPrompt'),
      options.title,
      {
        cancelButtonText: $t('button.cancel'),
        confirmButtonText: $t('approval.action.submit'),
        inputPlaceholder: $t('approval.placeholder.applicationReason'),
        inputType: 'textarea',
        inputValidator: (input: string) => {
          const normalized = String(input || '').trim();
          if (!normalized) {
            return $t('approval.message.applicationReasonRequired');
          }
          if (normalized.length > 500) {
            return $t('approval.message.applicationReasonTooLong');
          }
          return true;
        },
        type: 'info',
      },
    );
    return {
      applicationReason: String(value || '').trim(),
    };
  } catch {
    return null;
  }
}
