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

import sequelize from '../database.js';
import '../models/index.js';
import Accident from '../models/Accident.js';
import DiaryDate from '../models/DiaryDates.js';
import Club from '../models/Club.js';
import { createMember } from './utils/factories.js';
import accidentService from '../services/accidentService.js';

vi.mock('../utils/userUtils.js', async () => {
  const actual = await vi.importActual('../utils/userUtils.js');
  return {
    ...actual,
    checkAccess: vi.fn().mockResolvedValue(true),
    getUserByToken: vi.fn().mockResolvedValue({ id: 1 }),
  };
});

const token = 'test-token';

describe('accidentService', () => {
  beforeEach(async () => {
    await sequelize.sync({ force: true });
  });

  it('legt einen Unfall-Eintrag an, wenn alle Referenzen vorhanden sind', async () => {
    const club = await Club.create({ name: 'Accident Club' });
    const member = await createMember(club.id, { firstName: 'Alice', lastName: 'Accident' });
    const diaryDate = await DiaryDate.create({ clubId: club.id, date: '2025-01-01' });

    const result = await accidentService.createAccident(token, club.id, member.id, diaryDate.id, 'Verstauchung');

    expect(result).toBeTruthy();
    const stored = await Accident.findOne({ where: { diaryDateId: diaryDate.id } });
    expect(stored).not.toBeNull();
    expect(stored.accident).toBe('Verstauchung');
  });

  it('wirft Fehler, wenn Member nicht im selben Club ist', async () => {
    const club = await Club.create({ name: 'Club A' });
    const otherClub = await Club.create({ name: 'Club B' });
    const member = await createMember(otherClub.id, { firstName: 'Bob', lastName: 'B' });
    const diaryDate = await DiaryDate.create({ clubId: club.id, date: '2025-01-01' });

    await expect(
      accidentService.createAccident(token, club.id, member.id, diaryDate.id, 'Sturz')
    ).rejects.toThrow('Member not found');
  });

  it('liefert Unfälle samt Mitgliedern zurück', async () => {
    const club = await Club.create({ name: 'Club A' });
    const member = await createMember(club.id, { firstName: 'Clara', lastName: 'Club' });
    const diaryDate = await DiaryDate.create({ clubId: club.id, date: '2025-01-01' });
    await Accident.create({ memberId: member.id, diaryDateId: diaryDate.id, accident: 'Verstauchung' });

    const accidents = await accidentService.getAccidents(token, club.id, diaryDate.id);

    expect(accidents).toHaveLength(1);
    expect(accidents[0]).toMatchObject({ firstName: 'Clara', accident: 'Verstauchung' });
  });
});
