import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import type { StarsManager } from '../modules/telegram-manager/stars-manager.js';

interface StarsRouteOpts extends FastifyPluginOptions {
  starsManager: StarsManager;
}

export default async function starsRoutes(app: FastifyInstance, opts: StarsRouteOpts) {
  const { starsManager } = opts;

  // GET /characters/:id/stars — Stars earnings stats
  app.get('/characters/:id/stars', async (request, reply) => {
    const { id } = request.params as { id: string };
    const { period } = request.query as { period?: 'daily' | 'weekly' | 'monthly' };

    try {
      const revenue = await starsManager.getRevenue(id, period);
      return reply.status(200).send({ success: true, data: revenue });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  // GET /characters/:id/stars/transactions — Transaction history
  app.get('/characters/:id/stars/transactions', async (request, reply) => {
    const { id } = request.params as { id: string };
    const { type, status, limit, offset } = request.query as {
      type?: 'payment' | 'reaction';
      status?: 'pending' | 'completed' | 'refunded';
      limit?: string;
      offset?: string;
    };

    try {
      const transactions = await starsManager.getTransactions(id, {
        type,
        status,
        limit: limit ? Number(limit) : undefined,
        offset: offset ? Number(offset) : undefined,
      });
      return reply.status(200).send({ success: true, data: transactions });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });
}
