import client from "./client";

// ── Types ───────────────────────────────────────────────────────────

export type JiraLinkEntityType = "test" | "technique" | "campaign" | "evidence";
export type JiraSyncDirection = "aegis_to_jira" | "jira_to_aegis" | "bidirectional";

export interface JiraLink {
  id: string;
  entity_type: JiraLinkEntityType;
  entity_id: string;
  jira_issue_key: string;
  jira_issue_id: string | null;
  jira_project_key: string | null;
  jira_status: string | null;
  jira_priority: string | null;
  jira_assignee: string | null;
  jira_story_points: string | null;
  last_synced_at: string | null;
  created_at: string;
}

export interface JiraIssueResult {
  issue_key: string;
  summary: string;
  status: string;
  assignee: string | null;
  priority: string | null;
}

export interface JiraLinkCreatePayload {
  entity_type: JiraLinkEntityType;
  entity_id: string;
  jira_issue_key: string;
  sync_direction?: JiraSyncDirection;
}

// ── API Functions ───────────────────────────────────────────────────

/** Search Jira issues by JQL or free text. */
export async function searchJiraIssues(
  q: string,
  maxResults: number = 10,
): Promise<JiraIssueResult[]> {
  const { data } = await client.get<JiraIssueResult[]>("/jira/search", {
    params: { q, max_results: maxResults },
  });
  return data;
}

/** Create a new Jira link for an Aegis entity. */
export async function createJiraLink(
  payload: JiraLinkCreatePayload,
): Promise<JiraLink> {
  const { data } = await client.post<JiraLink>("/jira/links", payload);
  return data;
}

/** List Jira links, optionally filtered. */
export async function listJiraLinks(params?: {
  entity_type?: JiraLinkEntityType;
  entity_id?: string;
  /** Batch-fetch links for multiple entity IDs (passed as repeated query params). */
  entity_ids?: string[];
}): Promise<JiraLink[]> {
  // Axios doesn't repeat array params by default — build URLSearchParams manually
  if (params?.entity_ids && params.entity_ids.length > 0) {
    const p = new URLSearchParams();
    if (params.entity_type) p.append("entity_type", params.entity_type);
    for (const id of params.entity_ids) p.append("entity_ids", id);
    const { data } = await client.get<JiraLink[]>(`/jira/links?${p.toString()}`);
    return data;
  }
  const { data } = await client.get<JiraLink[]>("/jira/links", { params });
  return data;
}

/** Force sync a Jira link. */
export async function syncJiraLink(
  linkId: string,
): Promise<{ message: string; jira_status: string }> {
  const { data } = await client.post(`/jira/links/${linkId}/sync`);
  return data;
}

/** Delete a Jira link. */
export async function deleteJiraLink(linkId: string): Promise<void> {
  await client.delete(`/jira/links/${linkId}`);
}

/** Auto-create a Jira issue from an Aegis entity and link them. */
export async function createIssueFromEntity(
  entityType: JiraLinkEntityType,
  entityId: string,
): Promise<{ issue_key: string; link_id: string }> {
  const { data } = await client.post("/jira/create-issue", null, {
    params: { entity_type: entityType, entity_id: entityId },
  });
  return data;
}
