import { describe, it, expect, vi, beforeEach } from 'vitest';

vi.mock('@/lib/config', () => ({ getWebhookUrl: () => 'https://api.test' }));

const apiFetchMock = vi.fn();
vi.mock('@/utils/apiFetch', () => ({
  apiFetch: (...args: any[]) => apiFetchMock(...args),
}));

import { generateSocialMediaPosts, publishSocialMediaPost } from '@/features/photopost/api/socialPostService';

function okJson(data: any) {
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}
function status(code: number) {
  return new Response('', { status: code });
}

beforeEach(() => {
  apiFetchMock.mockReset();
});

describe('socialPostService API', () => {
  it('generateSocialMediaPosts posts payload and returns json', async () => {
    apiFetchMock.mockResolvedValueOnce(okJson({ output: {} }));

    const payload = { eventId: 'e1', images: ['img'], description: 'desc' };
    const result = await generateSocialMediaPosts(payload);

    expect(apiFetchMock).toHaveBeenCalledWith('https://api.test/socialmedia/post2event', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    expect(result).toEqual({ output: {} });
  });

  it('publishSocialMediaPost posts payload and returns json', async () => {
    apiFetchMock.mockResolvedValueOnce(okJson({ status: 'sucess' }));

    const args = { postId: 'p1', posts: {}, images: [], scheduledTime: '2025-01-01T00:00:00Z' };
    const result = await publishSocialMediaPost(args);

    expect(apiFetchMock).toHaveBeenCalledWith('https://api.test/socialmedia/publish_post', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(args),
    });
    expect(result).toEqual({ status: 'sucess' });
  });

  it('generateSocialMediaPosts returns null on non-ok', async () => {
    apiFetchMock.mockResolvedValueOnce(status(500));
    const res = await generateSocialMediaPosts({});
    expect(res).toBeNull();
  });
});
