import api, { ApiResponse } from './api';
import { uploadService } from './upload.service';
import { CmsContentRecord } from '@/types/cms';

/**
 * Check if a string looks like an S3 key (not a URL or local path).
 */
function isS3Key(value: string): boolean {
  if (!value) return false;
  return !value.startsWith('http') && !value.startsWith('/') && !value.startsWith('data:');
}

/**
 * Resolve an image value: if it's an S3 key, fetch a presigned download URL.
 * Otherwise return as-is (already a full URL or local path).
 */
export async function resolveImageUrl(value: string | undefined | null): Promise<string> {
  if (!value) return '';
  if (!isS3Key(value)) return value;
  try {
    return await uploadService.getPresignedDownloadUrl(value);
  } catch {
    return value;
  }
}

class CmsService {
  async getPageContent(pageSlug: string): Promise<CmsContentRecord[]> {
    try {
      const response = await api.get<ApiResponse<CmsContentRecord[]>>(`/cms/page/${pageSlug}`);
      return response.data.data;
    } catch {
      return [];
    }
  }

  async getSectionContent<T>(pageSlug: string, sectionKey: string): Promise<T | null> {
    try {
      const response = await api.get<ApiResponse<CmsContentRecord>>(`/cms/page/${pageSlug}/${sectionKey}`);
      return response.data.data.content as T;
    } catch {
      return null;
    }
  }
}

export const cmsService = new CmsService();
