import { FastifyInstance } from 'fastify';
import { authMiddleware } from '../middleware/auth.js';
import { householdService } from '../services/household.service.js';

export async function householdRoutes(app: FastifyInstance) {
  // Create a new household
  app.post('/api/households', { preHandler: [authMiddleware] }, async (request, reply) => {
    const { name } = request.body as { name: string };
    
    if (!name || name.trim() === '') {
      return reply.status(400).send({
        success: false,
        error: 'VALIDATION_ERROR',
        message: 'Household name is required'
      });
    }

    try {
      const household = await householdService.createHousehold(request.user!.id, name.trim());
      return reply.status(201).send({
        success: true,
        data: household
      });
    } catch (error: any) {
      if (error.message === 'USER_ALREADY_IN_HOUSEHOLD') {
        return reply.status(409).send({
          success: false,
          error: 'USER_ALREADY_IN_HOUSEHOLD',
          message: 'You are already a member of a household'
        });
      }
      
      app.log.error(error);
      return reply.status(500).send({
        success: false,
        error: 'INTERNAL_ERROR',
        message: 'Failed to create household'
      });
    }
  });

  // Get my household
  app.get('/api/households/mine', { preHandler: [authMiddleware] }, async (request, reply) => {
    try {
      const household = await householdService.getMyHousehold(request.user!.id);
      
      if (!household) {
        return reply.status(404).send({
          success: false,
          error: 'NO_HOUSEHOLD',
          message: 'You are not a member of any household'
        });
      }

      return reply.send({
        success: true,
        data: household
      });
    } catch (error: any) {
      app.log.error(error);
      return reply.status(500).send({
        success: false,
        error: 'INTERNAL_ERROR',
        message: 'Failed to get household'
      });
    }
  });

  // Join a household with invite code
  app.post('/api/households/join', { preHandler: [authMiddleware] }, async (request, reply) => {
    const { inviteCode } = request.body as { inviteCode: string };
    
    if (!inviteCode || inviteCode.trim() === '') {
      return reply.status(400).send({
        success: false,
        error: 'VALIDATION_ERROR',
        message: 'Invite code is required'
      });
    }

    try {
      const household = await householdService.joinHousehold(request.user!.id, inviteCode.trim().toUpperCase());
      return reply.send({
        success: true,
        data: household
      });
    } catch (error: any) {
      if (error.message === 'USER_ALREADY_IN_HOUSEHOLD') {
        return reply.status(409).send({
          success: false,
          error: 'USER_ALREADY_IN_HOUSEHOLD',
          message: 'You are already a member of a household'
        });
      }
      
      if (error.message === 'INVALID_INVITE_CODE') {
        return reply.status(404).send({
          success: false,
          error: 'INVALID_INVITE_CODE',
          message: 'Invalid invite code'
        });
      }
      
      app.log.error(error);
      return reply.status(500).send({
        success: false,
        error: 'INTERNAL_ERROR',
        message: 'Failed to join household'
      });
    }
  });

  // Regenerate invite code (owner only)
  app.post('/api/households/:id/invite', { preHandler: [authMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };

    try {
      const newInviteCode = await householdService.regenerateInviteCode(request.user!.id, id);
      
      return reply.send({
        success: true,
        data: { invite_code: newInviteCode }
      });
    } catch (error: any) {
      if (error.message === 'ONLY_OWNER_CAN_REGENERATE_INVITE') {
        return reply.status(403).send({
          success: false,
          error: 'FORBIDDEN',
          message: 'Only household owners can regenerate invite codes'
        });
      }
      
      app.log.error(error);
      return reply.status(500).send({
        success: false,
        error: 'INTERNAL_ERROR',
        message: 'Failed to regenerate invite code'
      });
    }
  });

  // Leave household
  app.delete('/api/households/:id/leave', { preHandler: [authMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };

    try {
      await householdService.leaveHousehold(request.user!.id, id);
      
      return reply.send({
        success: true,
        message: 'Successfully left household'
      });
    } catch (error: any) {
      if (error.message === 'NOT_HOUSEHOLD_MEMBER') {
        return reply.status(404).send({
          success: false,
          error: 'NOT_HOUSEHOLD_MEMBER',
          message: 'You are not a member of this household'
        });
      }
      
      if (error.message === 'OWNER_CANNOT_LEAVE_WITH_MEMBERS') {
        return reply.status(409).send({
          success: false,
          error: 'OWNER_CANNOT_LEAVE_WITH_MEMBERS',
          message: 'Household owners cannot leave while other members remain'
        });
      }
      
      app.log.error(error);
      return reply.status(500).send({
        success: false,
        error: 'INTERNAL_ERROR',
        message: 'Failed to leave household'
      });
    }
  });
}