import { describe, it, expect, beforeEach } from 'vitest';
import request from 'supertest';
import express, { type Express } from 'express';
import initSqlJs from 'sql.js';
import { createTagRoutes } from '../routes/tags.js';
import fs from 'fs';
import path from 'path';

describe('Tag API', () => {
  let app: Express;
  let db: any;

  beforeEach(async () => {
    const SQL = await initSqlJs();
    db = new SQL.Database();
    const schemaPath = path.join(process.cwd(), 'src/backend/db/schema.sql');
    const schema = fs.readFileSync(schemaPath, 'utf-8');
    db.exec(schema);
    app = express();
    app.use(express.json());
    app.use('/api/tags', createTagRoutes(db));
    // Create test recipe for tag assignment tests
    db.run('INSERT INTO recipes (title, created_at, updated_at) VALUES (?, ?, ?)', ['Test Recipe', Date.now(), Date.now()]);
  });

  describe('POST /api/tags', () => {
    it('should create a new tag', async () => {
      const response = await request(app)
        .post('/api/tags')
        .send({ name: 'Breakfast' })
        .expect(201);
      expect(response.body.success).toBe(true);
      expect(response.body.data).toMatchObject({ name: 'Breakfast' });
      expect(response.body.data.id).toBeDefined();
    });
    it('should reject empty name', async () => {
      const response = await request(app)
        .post('/api/tags')
        .send({ name: '' })
        .expect(400);
      expect(response.body.success).toBe(false);
    });
    it('should reject duplicate tag names', async () => {
      await request(app).post('/api/tags').send({ name: 'Breakfast' }).expect(201);
      const response = await request(app).post('/api/tags').send({ name: 'Breakfast' }).expect(400);
      expect(response.body.success).toBe(false);
    });
  });

  describe('GET /api/tags', () => {
    it('should list all tags', async () => {
      await request(app).post('/api/tags').send({ name: 'Breakfast' });
      await request(app).post('/api/tags').send({ name: 'Lunch' });
      await request(app).post('/api/tags').send({ name: 'Dinner' });
      const response = await request(app).get('/api/tags').expect(200);
      expect(response.body.success).toBe(true);
      expect(response.body.data).toHaveLength(3);
    });
  });
});
