import { request } from "./core";

// PROJ-51: Archiving rules (minimal PROJ-43) with optional retention period.
// Superadmin-only CRUD under /api/admin/archiving-rules.

// Condition types — must match storage.RuleCond* constants in the Go backend.
export type RuleConditionType =
  | "sender_domain"
  | "recipient_domain"
  | "sender_address"
  | "recipient_address";

export interface ArchivingRule {
  id: number;
  tenant_id: number | null; // null = applies to all tenants
  condition_type: RuleConditionType;
  pattern: string;
  priority: number;
  retention_days: number | null; // null = no rule-specific retention
  created_at: string;
}

export interface ArchivingRulesResponse {
  rules: ArchivingRule[];
  min_retention_days: number;
}

export interface ArchivingRuleInput {
  tenant_id: number | null;
  condition_type: RuleConditionType;
  pattern: string;
  priority: number;
  retention_days: number | null;
}

export async function getArchivingRules(): Promise<ArchivingRulesResponse> {
  return request<ArchivingRulesResponse>("/api/admin/archiving-rules");
}

export async function createArchivingRule(
  input: ArchivingRuleInput
): Promise<{ id: number }> {
  return request<{ id: number }>("/api/admin/archiving-rules", {
    method: "POST",
    body: JSON.stringify(input),
  });
}

export async function updateArchivingRule(
  id: number,
  input: ArchivingRuleInput
): Promise<void> {
  await request<void>(`/api/admin/archiving-rules/${id}`, {
    method: "PUT",
    body: JSON.stringify(input),
  });
}

export async function deleteArchivingRule(id: number): Promise<void> {
  await request<void>(`/api/admin/archiving-rules/${id}`, { method: "DELETE" });
}
