import type { TGuruRepository } from "./guru.repository";
import type { CreateTicketInput } from "./guru.schema";
import type { GuruTicket } from "@/internal/datastore/guru.types";
import { redactSensitive } from "@/internal/kevo/kevo.service";

/** The exact refusal wording from the spec — tests assert on it. */
export const EDIT_REFUSAL_MESSAGE =
  "Sorry, you don't have permission to update this member's information.";

export const normalizeEmail = (email: string) => email.trim().toLowerCase();

export const GuruServices = (deps: { GuruRepository: TGuruRepository }) => ({
  async createTicket(
    input: CreateTicketInput,
    owner: { id: string; email: string },
  ): Promise<GuruTicket> {
    const ticket = await deps.GuruRepository.insertTicket({
      console_user_id: owner.id,
      concierge_email: normalizeEmail(owner.email),
      member_ref: input.member_ref ?? null,
      category: input.category ?? null,
      summary: input.summary ? redactSensitive(input.summary) : null,
    });
    await deps.GuruRepository.insertAudit({
      ticket_id: ticket.id,
      action: "ticket.created",
      actor_email: owner.email,
      member_ref: ticket.member_ref,
      metadata: { category: ticket.category },
    });
    return ticket;
  },

  /**
   * The server-side write gate (spec §3): the logged-in user must be on the
   * edit allowlist. Never derived from anything the LLM says.
   */
  async canEdit(email: string): Promise<boolean> {
    return deps.GuruRepository.isAllowlisted(normalizeEmail(email));
  },

  async addToAllowlist(email: string, actorEmail: string) {
    const normalized = normalizeEmail(email);
    const entry = await deps.GuruRepository.addToAllowlist(
      normalized,
      actorEmail,
    );
    if (entry) {
      await deps.GuruRepository.insertAudit({
        action: "allowlist.added",
        actor_email: actorEmail,
        metadata: { email: normalized },
      });
    }
    return entry ?? null; // null = already on the list
  },

  async removeFromAllowlist(email: string, actorEmail: string) {
    const normalized = normalizeEmail(email);
    const removed = await deps.GuruRepository.removeFromAllowlist(normalized);
    if (removed) {
      await deps.GuruRepository.insertAudit({
        action: "allowlist.removed",
        actor_email: actorEmail,
        metadata: { email: normalized },
      });
    }
    return removed;
  },
});

export type TGuruServices = ReturnType<typeof GuruServices>;
