import { PrismaClient } from '@prisma/client';
import request from 'supertest';

import { app } from '../../../app';

const prisma = new PrismaClient();

describe('Auth API Integration Tests', () => {
    beforeAll(async () => {
        // Clean DB
        await prisma.$transaction([
            prisma.refreshToken.deleteMany(),
            prisma.user.deleteMany(),
        ]);
    });

    afterAll(async () => {
        await prisma.$disconnect();
    });

    beforeEach(async () => {
        await prisma.$transaction([
            prisma.refreshToken.deleteMany(),
            prisma.user.deleteMany(),
        ]);
    });

    describe('POST /auth/register', () => {
        it('should register a user with strong password', async () => {
            const res = await request(app)
                .post('/auth/register')
                .send({
                    email: 'test@example.com',
                    password: 'StrongPassword123!',
                    username: 'testuser'
                });

            expect(res.status).toBe(201);
            expect(res.body.success).toBe(true);
            expect(res.body.data.user.email).toBe('test@example.com');
        });

        it('should fail with weak password (Zod validation)', async () => {
            const res = await request(app)
                .post('/auth/register')
                .send({
                    email: 'weak@example.com',
                    password: 'weak',
                    username: 'weakuser'
                });

            expect(res.status).toBe(400);
            expect(res.body.success).toBe(false);
            expect(res.body.error.code).toBe('VALIDATION_ERROR');
        });
    });

    describe('POST /auth/login', () => {
        it('should login successfully', async () => {
            // Create user first
            await request(app)
                .post('/auth/register')
                .send({
                    email: 'login@example.com',
                    password: 'StrongPassword123!',
                    username: 'loginuser'
                });

            const res = await request(app)
                .post('/auth/login')
                .send({
                    email: 'login@example.com',
                    password: 'StrongPassword123!'
                });

            expect(res.status).toBe(200);
            expect(res.body.success).toBe(true);
            expect(res.body.data.tokens).toBeDefined();
        });
    });
});
