import { FastifyInstance } from 'fastify';
import { DbService } from '../services/db.service.js';

export default async function searchRoutes(fastify: FastifyInstance, options: { dbService: DbService }) {
  const { dbService } = options;

  fastify.get('/search', async (request, reply) => {
    const query = (request.query as any).q;
    if (!query) {
      return reply.code(400).send({ error: 'Query parameter "q" is required' });
    }

    try {
      // Typesense-first with a Postgres ILIKE fallback (Typesense isn't indexed yet).
      return await dbService.searchTracks(String(query));
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({ error: 'Search failed' });
    }
  });
}
