import client from "./client";
import type { Technique, TechniqueStatus, Test, IntelItem, DefensiveTechnique } from "../types/models";

/** Summary representation used in list endpoints. */
export interface TechniqueSummary {
  id: string;
  mitre_id: string;
  name: string;
  tactic: string | null;
  status_global: TechniqueStatus;
  review_required?: boolean;
}

/** Extended technique with tests for detail view. */
export interface TechniqueWithTests extends Technique {
  tests?: Test[];
  intel_items?: IntelItem[];
  d3fend_defenses?: DefensiveTechnique[];
}

export interface TechniqueFilters {
  tactic?: string;
  status?: TechniqueStatus;
  review_required?: boolean;
}

/** Fetch all techniques (summary). */
export async function getTechniques(filters?: TechniqueFilters): Promise<TechniqueSummary[]> {
  const params = new URLSearchParams();
  if (filters?.tactic) params.append("tactic", filters.tactic);
  if (filters?.status) params.append("status", filters.status);
  if (filters?.review_required !== undefined) {
    params.append("review_required", String(filters.review_required));
  }
  
  const { data } = await client.get<TechniqueSummary[]>(
    `/techniques${params.toString() ? `?${params}` : ""}`
  );
  return data;
}

/** Fetch a single technique by mitre_id (with tests). */
export async function getTechniqueByMitreId(mitreId: string): Promise<TechniqueWithTests> {
  const { data } = await client.get<TechniqueWithTests>(`/techniques/${mitreId}`);
  return data;
}

/** Mark a technique as reviewed. */
export async function markTechniqueReviewed(mitreId: string): Promise<TechniqueWithTests> {
  const { data } = await client.patch<TechniqueWithTests>(`/techniques/${mitreId}/review`);
  return data;
}
