import type {
  CounterpartItemDto,
  OrganizationInvitationHistoryItemDto,
} from '@/lib/api/organization';

export type InvitationLinkTarget = Pick<
  OrganizationInvitationHistoryItemDto,
  'id' | 'ownerEmail' | 'status' | 'acceptedAt'
>;

/** Cached after POST /organizations/invite because only tokenHash is persisted server-side. */
export type StoredOrganizationInviteLink = {
  invitationId: string;
  ownerEmail: string;
  invitationUrl: string;
};

export function organizationInviteLinksStorageKey(orgId: string): string {
  return `counterpartInviteLinks:${orgId}`;
}

export function readOrganizationInviteLinks(
  orgId: string,
): Record<string, StoredOrganizationInviteLink> {
  if (typeof window === 'undefined') return {};
  try {
    const raw = window.localStorage.getItem(organizationInviteLinksStorageKey(orgId));
    if (!raw) return {};
    const parsed = JSON.parse(raw) as Record<string, StoredOrganizationInviteLink>;
    return parsed && typeof parsed === 'object' ? parsed : {};
  } catch {
    return {};
  }
}

export function writeOrganizationInviteLinks(
  orgId: string,
  links: Record<string, StoredOrganizationInviteLink>,
): void {
  if (typeof window === 'undefined') return;
  window.localStorage.setItem(organizationInviteLinksStorageKey(orgId), JSON.stringify(links));
}

/** Show copy/regenerate only until the invitee accepts (first login / setup). */
export function canShareOrganizationInviteLink(
  invitation: Pick<OrganizationInvitationHistoryItemDto, 'status' | 'acceptedAt'>,
): boolean {
  if (invitation.acceptedAt) return false;
  return invitation.status === 'PENDING' || invitation.status === 'EXPIRED';
}

/**
 * Maps a connections-list row to copy/regenerate UI when it was created by the invitation flow.
 * Plain invite URLs are not stored in the DB; use localStorage (storeInviteLink) or POST …/link.
 */
export function invitationTargetFromConnectionRow(
  row: CounterpartItemDto,
  currentOrganizationId: string,
): InvitationLinkTarget | null {
  if (!row.pendingInvitationId) return null;
  if (row.requestedByOrganizationId !== currentOrganizationId) return null;
  return {
    id: row.pendingInvitationId,
    ownerEmail: row.ownerEmail,
    status: row.invitationStatus ?? 'PENDING',
    acceptedAt: null,
  };
}
