import jwt from '@fastify/jwt'
import Fastify from 'fastify'
import { afterAll, beforeEach, beforeAll, describe, expect, it } from 'vitest'
import { prisma } from '../../lib/prisma.js'
import { registerAuthSessionRoutes } from '../auth-session.js'

const JWT_SECRET = 'test-secret'

async function buildApp() {
  const app = Fastify({ logger: false })
  await app.register(jwt, { secret: JWT_SECRET })
  app.decorate('authenticate', async function (request, reply) {
    try {
      await request.jwtVerify()
    } catch {
      return reply.code(401).send({ error: 'Unauthorized' })
    }
  })
  app.decorate('eventBus', { emit: () => {} })
  await registerAuthSessionRoutes(app)
  await app.ready()
  return app
}

function signToken(app, userId, email) {
  return app.jwt.sign({ sub: userId, email })
}

async function createUser(email) {
  const user = await prisma.user.create({
    data: { email, displayName: 'Test', avatar: null, avatarStyle: 'avataaars' },
  })
  await prisma.notificationPreference.create({ data: { userId: user.id, globalEnabled: true } })
  return user
}

describe('GET /api/me/auth-methods', () => {
  let app, user, token
  const email = `test-methods-${Date.now()}@example.com`

  beforeAll(async () => {
    app = await buildApp()
  })
  afterAll(async () => {
    await prisma.notificationPreference.deleteMany({ where: { userId: user?.id } })
    await prisma.user.deleteMany({ where: { email } })
    await app.close()
  })

  beforeEach(async () => {
    await prisma.oAuthAccount.deleteMany({ where: { user: { email } } })
    await prisma.notificationPreference.deleteMany({ where: { user: { email } } })
    await prisma.user.deleteMany({ where: { email } })
    user = await createUser(email)
    token = signToken(app, user.id, email)
  })

  it('returns methods for user without any method', async () => {
    const res = await app.inject({
      method: 'GET',
      url: '/api/me/auth-methods',
      headers: { authorization: `Bearer ${token}` },
    })
    expect(res.statusCode).toBe(200)
    const body = JSON.parse(res.body)
    expect(body.methods.find((m) => m.type === 'password').active).toBe(false)
    expect(body.methods.find((m) => m.type === 'vk').active).toBe(false)
    expect(body.methods.find((m) => m.type === 'yandex').active).toBe(false)
  })

  it('returns password as active after setting it', async () => {
    await prisma.user.update({ where: { id: user.id }, data: { passwordHash: 'hashed' } })
    const res = await app.inject({
      method: 'GET',
      url: '/api/me/auth-methods',
      headers: { authorization: `Bearer ${token}` },
    })
    expect(JSON.parse(res.body).methods.find((m) => m.type === 'password').active).toBe(true)
  })
})
