export function mapReportRow(row: any, is_owner: boolean, liked_by_me: boolean): any {
  return {
    id: row.id,
    user_id: row.user_id,
    status: row.status,
    pet_type: row.pet_type,
    pet_name: row.pet_name,
    breed: row.breed,
    size: row.size,
    color: row.color,
    markings: row.markings,
    photo_uri: row.photo_uri,
    photo_uris: typeof row.photo_uris === 'string' ? JSON.parse(row.photo_uris) : row.photo_uris || [],
    description: row.description,
    latitude: Number(row.latitude),
    longitude: Number(row.longitude),
    location_name: row.location_name,
    last_seen_date: row.last_seen_date,
    reward: row.reward,
    rewardPool: Number(row.reward_pool || 0),
    contact_name: row.contact_name,
    contact_phone: row.contact_phone,
    showContactPublic: row.show_contact_public !== false,
    created_at: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
    is_owner,
    comments: [],
    timeline: [],
    reunion_message: row.reunion_message || undefined,
    reunion_date: row.reunion_date
      ? row.reunion_date instanceof Date
        ? row.reunion_date.toISOString()
        : row.reunion_date
      : undefined,
    likes: Number(row.likes || 0),
    liked_by_me,
    is_boosted: row.is_boosted || false,
    boosted_at: row.boosted_at
      ? row.boosted_at instanceof Date
        ? row.boosted_at.toISOString()
        : row.boosted_at
      : undefined,
    boost_expires_at: row.boost_expires_at
      ? row.boost_expires_at instanceof Date
        ? row.boost_expires_at.toISOString()
        : row.boost_expires_at
      : undefined,
    is_reunited: row.is_reunited || false,
    is_active: row.is_active !== false,
  };
}

export function mapProfileRow(row: any): any {
  return {
    id: row.id,
    user_id: row.user_id,
    pet_type: row.pet_type,
    pet_name: row.pet_name,
    breed: row.breed,
    size: row.size,
    color: row.color,
    markings: row.markings,
    photo_uris: typeof row.photo_uris === 'string' ? JSON.parse(row.photo_uris) : row.photo_uris || [],
    biometricphoto_uris:
      typeof row.biometric_photo_uris === 'string'
        ? JSON.parse(row.biometric_photo_uris)
        : row.biometric_photo_uris || [],
    microchip_number: row.microchip_number,
    medicalNotes: row.medical_notes,
    suburb: row.suburb,
    ownerName: row.owner_name,
    ownerPhone: row.owner_phone,
    created_at: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
    updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : row.updated_at,
    is_active: row.is_active !== false,
  };
}

export function maskPublicContactName(name: string | null | undefined): string {
  const raw = (name || '').trim();
  if (!raw) return 'Bi***sh';
  if (raw.length <= 2) return `${raw.charAt(0) || 'B'}***`;
  if (raw.length <= 4) return `${raw.slice(0, 1)}***${raw.slice(-1)}`;
  return `${raw.slice(0, 2)}***${raw.slice(-2)}`;
}

export function maskPublicContactPhone(phone: string | null | undefined): string {
  const digits = String(phone || '').replace(/\D/g, '');
  if (!digits) return '42XXXX';
  return `${digits.slice(0, 2).padEnd(2, '4')}XXXX`;
}

export function applyPublicReportMask<T extends Record<string, any>>(report: T): T {
  return {
    ...report,
    contact_name: maskPublicContactName(report.contact_name),
    contact_phone: maskPublicContactPhone(report.contact_phone),
  };
}

const ASSET_CDN_URL = 'https://cdn.thefurfinder.com';

/** Tags an external (scraped) image URL so the client's CDN-proxy layer knows to fetch/cache it. */
export function makeScrapedPhotoAssetSafe(value: unknown): string {
  const rawUri = String(value || '').trim();
  if (!rawUri || rawUri.includes(ASSET_CDN_URL)) return rawUri;

  const absoluteUri = rawUri.startsWith('//') ? `https:${rawUri}` : rawUri;
  if (!/^https?:\/\//i.test(absoluteUri)) return absoluteUri;

  try {
    const url = new URL(absoluteUri);
    const currentHash = url.hash.replace(/^#/, '');
    url.hash = currentHash ? `${currentHash}&${ASSET_CDN_URL}` : ASSET_CDN_URL;
    return url.toString();
  } catch {
    return `${absoluteUri}#${ASSET_CDN_URL}`;
  }
}

/** Maps a row from the `unified_reports` CTE (internal `pet_reports` + external `scrapped_pet_report`). */
export function mapUnifiedReportRow(row: any, isOwner: boolean, likedByMe: boolean): any {
  const mapped = mapReportRow(row, isOwner, likedByMe);
  const isExternal = row.report_source === 'scraped';

  if (isExternal) {
    mapped.photo_uris = mapped.photo_uris.map(makeScrapedPhotoAssetSafe);
    mapped.photo_uri = makeScrapedPhotoAssetSafe(mapped.photo_uri || mapped.photo_uris[0] || '');
  }

  return {
    ...mapped,
    report_source: row.report_source || 'internal',
    is_external: isExternal,
    details_url: row.details_url || undefined,
    website_id: row.website_id || undefined,
    scraped_animal_id: row.scraped_animal_id || undefined,
    contact_email: row.contact_email || undefined,
    scraped_at: row.scraped_at instanceof Date ? row.scraped_at.toISOString() : row.scraped_at || undefined,
  };
}
