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

vi.mock('../services/emailService.js', () => ({
  sendActivationEmail: vi.fn().mockResolvedValue(),
}));

import { setupRouteAuthMocks } from './utils/routeAuthMocks.js';

setupRouteAuthMocks();

import app from './testApp.js';
import sequelize from '../database.js';
import User from '../models/User.js';
import Club from '../models/Club.js';
import UserClub from '../models/UserClub.js';
import DiaryDate from '../models/DiaryDates.js';
import { createMember } from './utils/factories.js';

const registerAndActivate = async (email) => {
  const password = 'Test123!';
  await request(app).post('/api/auth/register').send({ email, password });
  const user = await User.findOne({ where: { email } });
  await user.update({ isActive: true });
  return { user, credentials: { email, password } };
};

const loginAndGetToken = async (credentials) => {
  const response = await request(app).post('/api/auth/login').send(credentials);
  return response.body.token;
};

const authHeaders = (token) => ({
  Authorization: `Bearer ${token}`,
  authcode: token,
});

describe('Accident Routes', () => {
  beforeEach(async () => {
    await sequelize.sync({ force: true });
    vi.mock('../utils/userUtils.js', () => ({
      checkAccess: vi.fn().mockResolvedValue(true),
      getUserByToken: vi.fn().mockResolvedValue({ id: 1 }),
      hasUserClubAccess: vi.fn().mockResolvedValue(true),
    }));
  });

  it('legt einen Unfall an und gibt ihn zurück', async () => {
    const { user, credentials } = await registerAndActivate('accident@example.com');
    const token = await loginAndGetToken(credentials);
    const club = await Club.create({ name: 'Accident Club' });
    await UserClub.create({ userId: user.id, clubId: club.id, role: 'admin', approved: true, isOwner: true });
    const member = await createMember(club.id, { firstName: 'Anna', lastName: 'Accident' });
    const diaryDate = await DiaryDate.create({ clubId: club.id, date: '2025-01-01' });

    const createResponse = await request(app)
      .post('/api/accident')
      .set(authHeaders(token))
      .send({ clubId: club.id, memberId: member.id, diaryDateId: diaryDate.id, accident: 'Verletzung' });

    expect(createResponse.status).toBe(201);

    const listResponse = await request(app)
      .get(`/api/accident/${club.id}/${diaryDate.id}`)
      .set(authHeaders(token));

    expect(listResponse.status).toBe(200);
    expect(listResponse.body).toHaveLength(1);
    expect(listResponse.body[0]).toMatchObject({ firstName: 'Anna' });
  });

  it('verhindert Anlage eines Unfalls ohne Authentifizierung', async () => {
    const response = await request(app)
      .post('/api/accident')
      .send({ clubId: 1, memberId: 1, diaryDateId: 1, accident: 'Test' });

    expect(response.status).toBe(401);
  });
});
