import { FastifyInstance } from 'fastify';
import { ConnectionService } from '../services/connection.service';
import { authMiddleware, adminMiddleware } from '../middleware/auth';

const connectionService = new ConnectionService();

export async function connectionRoutes(app: FastifyInstance): Promise<void> {
  // 需要认证的路由
  app.post('/api/connections/request', { preHandler: [authMiddleware] }, async (request, reply) => {
    try {
      const { device_id, node_id } = request.body as { device_id: number; node_id: number };
      if (!device_id || !node_id) {
        return reply.status(400).send({
          success: false, error: 'VALIDATION_ERROR',
          message: 'device_id and node_id are required',
        });
      }
      const result = await connectionService.requestConnection(request.user!.user_id, { device_id, node_id });
      return reply.send({ success: true, data: result });
    } catch (err: any) {
      if (err.message === 'DEVICE_NOT_FOUND') {
        return reply.status(404).send({
          success: false, error: 'DEVICE_NOT_FOUND',
          message: 'Device not found or not owned by user',
        });
      }
      if (err.message === 'NODE_NOT_AVAILABLE') {
        return reply.status(400).send({
          success: false, error: 'NODE_NOT_AVAILABLE',
          message: 'Node not available',
        });
      }
      throw err;
    }
  });

  // verify-token 不需要用户认证（由 Relay Node 调用）
  app.post('/api/connections/verify-token', async (request, reply) => {
    const { token, device_id } = request.body as { token: string; device_id: number };
    if (!token || !device_id) {
      return reply.status(400).send({
        success: false, error: 'VALIDATION_ERROR',
        message: 'token and device_id are required',
      });
    }
    const result = await connectionService.verifyToken({ token, device_id });
    return reply.send({ success: true, data: result });
  });

  app.post('/api/connections/disconnect', { preHandler: [authMiddleware] }, async (request, reply) => {
    const { device_id } = request.body as { device_id: number };
    if (!device_id) {
      return reply.status(400).send({
        success: false, error: 'VALIDATION_ERROR',
        message: 'device_id is required',
      });
    }
    await connectionService.disconnect(request.user!.user_id, device_id);
    return reply.send({ success: true, message: 'Disconnected' });
  });

  app.get('/api/connections/logs', { preHandler: [authMiddleware] }, async (request, reply) => {
    const logs = await connectionService.getUserLogs(request.user!.user_id);
    return reply.send({ success: true, data: logs });
  });

  app.get('/api/admin/connections/logs', { preHandler: [authMiddleware, adminMiddleware] }, async (_request, reply) => {
    const logs = await connectionService.getLogs();
    return reply.send({ success: true, data: logs });
  });
}
