import type { TKevoRepository } from "./kevo.repository";
import type { FlagIssueInput } from "./kevo.schema";
import type { KevoFlag, KevoFlagSource } from "@/internal/datastore/kevo.types";

const EMAIL_RE = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;
// 7+ digits with optional spaces/dashes/dots between them (phone numbers,
// card fragments). Shorter runs (years, room numbers, prices) pass through.
const LONG_NUMBER_RE = /\+?\d(?:[\s().-]?\d){6,}/g;

/**
 * Flag text comes from live member conversations. Contact data must never be
 * stored in a flag (org policy + task spec), so every free-text field is
 * scrubbed on the way in. ponytail: regex heuristic — misses spelled-out
 * numbers; swap for a PII library if reviewers ever find leaks.
 */
export const redactSensitive = (text: string): string =>
  text
    .replace(EMAIL_RE, "[email redacted]")
    .replace(LONG_NUMBER_RE, "[number redacted]");

const scrub = (v: string | undefined) =>
  v === undefined ? undefined : redactSensitive(v);

export const KevoServices = (deps: { KevoRepository: TKevoRepository }) => ({
  async createFlag(
    input: FlagIssueInput,
    source: KevoFlagSource,
    actorEmail?: string,
  ): Promise<{ flag: KevoFlag; created: boolean }> {
    const { flag, created } = await deps.KevoRepository.insertFlag({
      source,
      category: input.category,
      conversation_id: input.conversation_id,
      member_id: input.member_id ?? null,
      member_question: scrub(input.member_question) ?? null,
      agent_answer: scrub(input.agent_answer) ?? null,
      member_claim: scrub(input.member_claim) ?? null,
      entity: input.entity ?? null,
      requested_change: scrub(input.requested_change) ?? null,
    });

    if (created) {
      await deps.KevoRepository.insertAudit({
        flag_id: flag.id,
        action: "flag.created",
        actor_email: actorEmail ?? null,
        metadata: { source, category: flag.category, entity: flag.entity },
      });
    }
    return { flag, created };
  },

  /** Reviewer action: status transition and/or notes, always audited. */
  async reviewFlag(
    reference: string,
    patch: { status?: string; reviewer_notes?: string },
    reviewer: { id: string; email: string },
  ): Promise<KevoFlag | null> {
    const flag = await deps.KevoRepository.getFlagByReference(reference);
    if (!flag) return null;
    const updated = await deps.KevoRepository.updateFlag(flag.id, {
      ...(patch.status ? { status: patch.status } : {}),
      ...(patch.reviewer_notes !== undefined
        ? { reviewer_notes: patch.reviewer_notes }
        : {}),
      reviewer_id: reviewer.id,
    });
    await deps.KevoRepository.insertAudit({
      flag_id: flag.id,
      action: patch.status ? "flag.status_changed" : "flag.notes_updated",
      actor_email: reviewer.email,
      metadata: patch.status
        ? { from: flag.status, to: patch.status }
        : undefined,
    });
    return updated;
  },

  async createKnowledge(
    input: {
      flag_id?: string;
      entity: string;
      aliases: string[];
      property?: string;
      category: string;
      verified_text: string;
    },
    actorEmail: string,
  ) {
    const entry = await deps.KevoRepository.insertKnowledge({
      flag_id: input.flag_id ?? null,
      entity: input.entity,
      aliases: input.aliases,
      property: input.property ?? null,
      category: input.category,
      verified_text: input.verified_text,
    });
    await deps.KevoRepository.insertAudit({
      entry_id: entry.id,
      flag_id: entry.flag_id,
      action: "entry.created",
      actor_email: actorEmail,
      metadata: { entity: entry.entity },
    });
    return entry;
  },

  async updateKnowledge(
    id: string,
    patch: Record<string, unknown>,
    actorEmail: string,
  ) {
    const entry = await deps.KevoRepository.updateKnowledge(id, patch);
    await deps.KevoRepository.insertAudit({
      entry_id: entry.id,
      action: "entry.updated",
      actor_email: actorEmail,
    });
    return entry;
  },

  /** Approve an entry; its linked flag (if any) moves to APPROVED too. */
  async approveKnowledge(id: string, actor: { id: string; email: string }) {
    const entry = await deps.KevoRepository.updateKnowledge(id, {
      status: "APPROVED",
      approved_by: actor.email,
      approved_at: new Date(),
    });
    await deps.KevoRepository.insertAudit({
      entry_id: entry.id,
      flag_id: entry.flag_id,
      action: "entry.approved",
      actor_email: actor.email,
    });
    if (entry.flag_id) {
      await deps.KevoRepository.updateFlag(entry.flag_id, {
        status: "APPROVED",
        reviewer_id: actor.id,
      });
      await deps.KevoRepository.insertAudit({
        flag_id: entry.flag_id,
        action: "flag.status_changed",
        actor_email: actor.email,
        metadata: { to: "APPROVED", via: "entry.approved" },
      });
    }
    return entry;
  },

  async retireKnowledge(id: string, actorEmail: string) {
    const entry = await deps.KevoRepository.updateKnowledge(id, {
      status: "RETIRED",
    });
    await deps.KevoRepository.insertAudit({
      entry_id: entry.id,
      action: "entry.retired",
      actor_email: actorEmail,
    });
    return entry;
  },
});

export type TKevoServices = ReturnType<typeof KevoServices>;
