import {
  aggregateAcrossTeams,
  formatAggregationResult,
  loopGet,
} from "../lib/loop-api.js";

// ─── Loop API V2: /team ────────────────────────────────────────
// Fields: apiKey (redacted), clientName, teamName,
//   address1, address2, address3, email, phoneNumber, websiteUrl,
//   primaryDarkColour, primaryLightColour, secondaryDarkColour,
//   secondaryLightColour, legalName, websiteContactUrl,
//   websitePropertiesUrl, dateCreated,
//   members[] (each: id, firstName, lastName, email, mobilePhone,
//     jobTitle, signatureImageUrl, avatarImage, avatarMedium,
//     avatarThumbnail, biography, customUrl, twitterUrl)
// ────────────────────────────────────────────────────────────────
interface LoopTeam {
  clientName?: string;
  teamName?: string;
  address1?: string;
  address2?: string;
  address3?: string;
  email?: string;
  phoneNumber?: string;
  websiteUrl?: string;
  legalName?: string;
  dateCreated?: string;
  members?: LoopTeamMember[];
  [key: string]: unknown;
}

interface LoopTeamMember {
  id: string;
  firstName?: string;
  lastName?: string;
  email?: string;
  mobilePhone?: string;
  jobTitle?: string;
  biography?: string;
  [key: string]: unknown;
}

export async function teamInfo(params: {
  accountId: string;
  teamName?: string;
}): Promise<string> {
  const { accountId, teamName } = params;

  const result = await aggregateAcrossTeams<LoopTeam>(
    accountId,
    "team",
    "loop-team-info",
    async (apiKey, team) => {
      const data = await loopGet<LoopTeam>(
        apiKey,
        "/team",
        "loop-team-info",
        team
      );
      // /team returns a single object, not an array
      if (data && typeof data === "object" && !Array.isArray(data)) {
        return [data];
      }
      return Array.isArray(data) ? data : [];
    },
    { teamName }
  );

  return formatAggregationResult(
    result,
    (t) => {
      const name = t.teamName ?? t.clientName ?? "Unknown";
      const client = t.clientName && t.clientName !== t.teamName ? ` (${t.clientName})` : "";
      const addr = t.address1 ? ` — ${t.address1}` : "";
      const phone = t.phoneNumber ? ` | ${t.phoneNumber}` : "";
      const email = t.email ? ` | ${t.email}` : "";
      const web = t.websiteUrl ? ` | ${t.websiteUrl}` : "";

      const lines = [`- **${name}**${client}${addr}${phone}${email}${web}`];

      if (t.members?.length) {
        lines.push(`  Team members (${t.members.length}):`);
        for (const m of t.members) {
          const mName = [m.firstName, m.lastName].filter(Boolean).join(" ");
          const title = m.jobTitle ? ` (${m.jobTitle})` : "";
          const mEmail = m.email ? ` — ${m.email}` : "";
          lines.push(`    - ${mName} [ID: ${m.id}]${title}${mEmail}`);
        }
      }

      return lines.join("\n");
    },
    "teams"
  );
}
