import { createLocalAccount } from '../services/account.service.js';
import { getFreeStarterSlotsCount } from '../services/planet.service.js';

export const registerInternalAccount = async (req, res) => {
  const { lobby_uuid, username, gender } = req.body;

  if (!lobby_uuid || !username || !gender) {
    return res.status(400).json({ 
      error: 'ERR_MISSING_REQUIRED_FIELDS' 
    });
  }

  try {
    const { local_uuid, triggerSectorClose } = await createLocalAccount(lobby_uuid, username, gender);

    return res.status(201).json({
      message: 'MSG_ACCOUNT_CREATED_SUCCESSFULLY',
      account: { local_uuid },
      triggerSectorClose: triggerSectorClose
    });

  } catch (error) {
    console.error('❌ Fehler bei interner Account-Registrierung:', error);

    if (error.code === 'ERR_SECTOR_FULL') {
      return res.status(503).json({ 
        error: 'ERR_SECTOR_FULL' 
      });
    }

    if (error.code === '23505') {
      return res.status(409).json({ 
        error: 'ERR_ACCOUNT_ALREADY_EXISTS' 
      });
    }

    return res.status(500).json({ 
      error: 'ERR_INTERNAL_SERVER_ERROR' 
    });
  }
};

/**
 * Liefert die Anzahl der freien Startplätze für die Lobby zurück.
 */
export const getSectorSlotStatus = async (req, res) => {
    try {
        const freeSlots = await getFreeStarterSlotsCount();
        return res.status(200).json({ 
          freeSlots 
        });
        
    } catch (error) {
        console.error('❌ Fehler beim Abrufen der Sektor-Slots:', error);
        return res.status(500).json({ 
          error: 'ERR_INTERNAL_SERVER_ERROR' 
        });
    }
};