import type { SuggestionDraft, ActivityDraft, MutualAidDraft, UserBranch, ConversationDraft } from "../types";
import { emptyDraft } from "./formatters";
import { extractTopic, detectMutualAidType } from "./intent";
import { SUGGESTION_KEYWORDS, ACTIVITY_KEYWORDS, MUTUAL_AID_KEYWORDS } from "../constants";

export function buildSuggestionDraftFromTopic(text: string, branch?: UserBranch): SuggestionDraft {
  const topic = extractTopic(text, SUGGESTION_KEYWORDS);
  return {
    title: `${topic}方面的建言`,
    summary: `围绕${topic}提出一条可执行、可落地的改进建议。`,
    body: `建议围绕"${topic}"建立更清晰的推进机制，进一步明确目标、责任人与时间节点，并结合平台现有资源形成宣传、服务、活动联动的闭环，持续提升会员参与感与服务质量。`,
    branchIds: branch ? [branch.id] : undefined,
    branchName: branch?.name
  };
}

export function buildActivityDraftFromTopic(text: string, branch?: UserBranch): ActivityDraft {
  const topic = extractTopic(text, ACTIVITY_KEYWORDS);
  return {
    title: `${topic}主题活动`,
    description: `围绕${topic}组织一次交流与分享活动，便于会员参与、互动和资源对接。`,
    branchIds: branch ? [branch.id] : undefined,
    branchName: branch?.name
  };
}

export function buildMutualAidDraftFromTopic(text: string, branch?: UserBranch): MutualAidDraft {
  const topic = extractTopic(text, MUTUAL_AID_KEYWORDS);
  const postType = detectMutualAidType(text) || "resource";
  return {
    postType,
    title: `${topic}${postType === "need" ? "需求" : "资源"}发布`,
    description: `围绕${topic}整理一条企业互助${postType === "need" ? "需求" : "资源"}信息，便于平台内进一步对接。`,
    branchId: branch?.id,
    branchName: branch?.name
  };
}

export function buildSuggestionPayload(draft: SuggestionDraft) {
  return {
    type: "suggestion",
    title: draft.title || "",
    summary: draft.summary || "",
    body: draft.body || "",
    branchIds: draft.branchIds || []
  };
}

export function buildActivityPayload(draft: ActivityDraft) {
  return {
    title: draft.title || "",
    description: draft.description || "",
    location: draft.location || "",
    startsAt: draft.startsAt || "",
    endsAt: draft.endsAt || "",
    registerDeadline: draft.registerDeadline || null,
    capacity: draft.capacity || null,
    branchIds: draft.branchIds || []
  };
}

export function buildMutualAidPayload(draft: MutualAidDraft) {
  return {
    postType: draft.postType || "",
    title: draft.title || "",
    description: draft.description || "",
    branchId: draft.branchId || 0,
    contactPhone: draft.contactPhone || "",
    contactWechat: draft.contactWechat || "",
    tagsText: draft.tagsText || "",
    publisherTitle: draft.publisherTitle || ""
  };
}
