import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { AttachmentUploader } from '../attachment-uploader';

const uploadMock = vi.fn();
vi.mock('@/lib/api', () => ({
  api: {
    messages: { uploadAttachment: (...a: unknown[]) => uploadMock(...a) },
  },
}));

describe('AttachmentUploader', () => {
  beforeEach(() => uploadMock.mockReset());

  it('uploads selected files and invokes onChange with attachment ids', async () => {
    uploadMock.mockResolvedValueOnce({
      data: { id: 'att-1', url: '/u1.jpg', content_type: 'image/jpeg', size_bytes: 100 },
    });
    const onChange = vi.fn();
    render(<AttachmentUploader orderId="o1" onChange={onChange} />);

    const file = new File(['x'], 'damage.jpg', { type: 'image/jpeg' });
    fireEvent.change(screen.getByLabelText(/Attach images/i), {
      target: { files: [file] },
    });

    await waitFor(() => expect(onChange).toHaveBeenCalledWith(['att-1']));
  });

  it('caps at 4 attachments', async () => {
    let counter = 0;
    uploadMock.mockImplementation(() => {
      counter += 1;
      return Promise.resolve({
        data: {
          id: `att-${counter}`,
          url: `/u${counter}.jpg`,
          content_type: 'image/jpeg',
          size_bytes: 1,
        },
      });
    });

    render(<AttachmentUploader orderId="o1" onChange={() => {}} />);

    const four = [0, 1, 2, 3].map(
      (i) => new File(['x'], `${i}.jpg`, { type: 'image/jpeg' }),
    );
    fireEvent.change(screen.getByLabelText(/Attach images/i), {
      target: { files: four },
    });
    await waitFor(() => expect(uploadMock).toHaveBeenCalledTimes(4));

    fireEvent.change(screen.getByLabelText(/Attach images/i), {
      target: {
        files: [new File(['x'], 'fifth.jpg', { type: 'image/jpeg' })],
      },
    });
    expect(screen.getByText(/Limit/i)).toBeInTheDocument();
  });
});
