import { ChatInputCommandInteraction } from "discord.js";
import { cfg } from "../../systems/config";
import { resolveUser, hasOfficerRole } from "../../systems/users";
import { setActiveCharacter } from "../../systems/characters";
import { setSessionBorrow } from "../../systems/borrow";
import { replyAndDelete } from "../../utils";
import fs from "fs";
import path from "path";

const CHARS_PATH = path.join(__dirname, "../../../data/characters.json");

function findSharedChar(usermapKey: string, charName: string): { ownerKey: string; charName: string } | null {
  try {
    const chars = JSON.parse(fs.readFileSync(CHARS_PATH, "utf8"));
    for (const [ownerKey, data] of Object.entries(chars) as [string, any][]) {
      if (ownerKey === usermapKey) continue;
      const char = data.characters?.find(
        (c: any) => c.name.toLowerCase() === charName.toLowerCase() && c.sharedWith?.includes(usermapKey)
      );
      if (char) return { ownerKey, charName: char.name };
    }
  } catch {}
  return null;
}

export async function handleCharSetActive(interaction: ChatInputCommandInteraction): Promise<void> {
  const member    = await interaction.guild!.members.fetch(interaction.user.id);
  const isOfficer = hasOfficerRole(member, cfg("officerRoles"));
  const nameArg   = interaction.options.getString("name");
  const charName  = interaction.options.getString("char_name", true);

  let usermapKey: string | null;
  if (nameArg) {
    if (!isOfficer) return void replyAndDelete(interaction, "❌ Only officers can manage other players' characters.");
    usermapKey = nameArg;
  } else {
    const user = await resolveUser(member);
    usermapKey = user.usermapKey;
  }

  if (!usermapKey) return void replyAndDelete(interaction, "❌ You are not registered in the system.");

  // Try own characters first
  const set = setActiveCharacter(usermapKey, charName);
  if (set) return void replyAndDelete(interaction, `✅ **${charName}** is now your active character.`);

  // Fall back to shared characters
  const shared = findSharedChar(usermapKey, charName);
  if (shared) {
    setSessionBorrow(usermapKey, shared.ownerKey, shared.charName);
    return void replyAndDelete(interaction, `✅ **${charName}** (shared by **${shared.ownerKey}**) set as active for this session.`);
  }

  return void replyAndDelete(interaction, `❌ No character named **${charName}** found.`);
}