import React from 'react';
import {render, screen, waitFor, fireEvent} from '@testing-library/react';
import CommentSection from '../CommentSection';
import {getCommentsByEvenement, updateComment} from '@/services/commentService';

const mockUseAuth = jest.fn();
jest.mock('@/services/commentService');
jest.mock('@/contexts/AuthContext', () => ({
  useAuth: () => mockUseAuth(),
}));
jest.mock('next/link', () => {
  return ({children, href, ...props}: {children: React.ReactNode; href: string; [key: string]: unknown}) => (
    <a href={href} {...props}>{children}</a>
  );
});

const mockedGetComments = getCommentsByEvenement as jest.Mock;
const commentByBreizh56 = {id: 3, texte: 'Super fest-noz', date: '2026-09-17', heure: '10:00', auteur: {id: 42, pseudo: 'breizh56'}};

function signedInAs(username: string | null) {
  mockUseAuth.mockReturnValue({
    isAuthenticated: username !== null,
    user: username === null ? null : {id: '1', username},
  });
}

describe('CommentSection', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    mockedGetComments.mockResolvedValue([commentByBreizh56]);
  });

  it('shouldLetTheAuthorEditTheirComment', async () => {
    signedInAs('breizh56');
    (updateComment as jest.Mock).mockResolvedValue({...commentByBreizh56, texte: 'Super fest-noz, on y retourne !'});
    render(<CommentSection evenementId={10} />);
    await waitFor(() => expect(screen.getByText('Super fest-noz')).toBeInTheDocument());

    fireEvent.click(screen.getByRole('button', {name: 'edit'}));
    const zone = screen.getByLabelText('edit_label') as HTMLTextAreaElement;
    expect(zone.value).toBe('Super fest-noz');
    fireEvent.change(zone, {target: {value: 'Super fest-noz, on y retourne !'}});
    fireEvent.click(screen.getByRole('button', {name: 'save'}));

    await waitFor(() => expect(updateComment).toHaveBeenCalledWith(3, 'Super fest-noz, on y retourne !'));
    expect(screen.getByText('Super fest-noz, on y retourne !')).toBeInTheDocument();
  });

  it('shouldNotOfferEditToOtherUsers', async () => {
    signedInAs('yann22');
    render(<CommentSection evenementId={10} />);
    await waitFor(() => expect(screen.getByText('Super fest-noz')).toBeInTheDocument());

    expect(screen.queryByRole('button', {name: 'edit'})).not.toBeInTheDocument();
  });

  it('shouldShowTheEmptyTextAndALoginLinkToAnonymousVisitors', async () => {
    signedInAs(null);
    mockedGetComments.mockResolvedValue([]);
    render(<CommentSection evenementId={10} />);
    await waitFor(() => expect(screen.getByText('empty')).toBeInTheDocument());

    expect(screen.getByText('login_to_comment').closest('a')).toHaveAttribute('href', '/connexion');
  });
});
