import pool from '../db.js';
import { getSectorSettings } from './config.service.js';
import { findNextAvailableStarterCoordinates } from './planet.service.js';
import { generateStarterPlanetStats } from '../utils/planet.util.js';

/**
 * Erstellt einen neuen Sektor-Account samt Heimatplanet in einer sicheren Datenbank-Transaktion.
 * 
 * @param {string} lobby_uuid - Die UUID des Nutzers aus der Lobby.
 * @param {string} username - Der Anzeigename.
 * @param {string} gender - Das Geschlecht des Commanders.
 * 
 * @returns {Promise<{local_uuid: string, triggerSectorClose: boolean}>}
 */
export const createLocalAccount = async (lobby_uuid, username, gender) => {
    const client = await pool.connect();
    
    try {
        await client.query('BEGIN');

        const { galaxy, system, position, triggerSectorClose } = await findNextAvailableStarterCoordinates();
        const planetStats = generateStarterPlanetStats(position);

        const settings = getSectorSettings();
        const initialPremium = settings.account_registration_bonus.initial_res_premium;

        const accountInsertQuery = `
            INSERT INTO local_accounts (lobby_uuid, username, gender, res_premium)
            VALUES ($1, $2, $3, $4)
            RETURNING local_uuid
        `;
        const accountResult = await client.query(accountInsertQuery, [
            lobby_uuid, 
            username, 
            gender, 
            initialPremium
        ]);
        
        const local_uuid = accountResult.rows[0].local_uuid;

        const planetName = "Unbekannter Planet"; 
        const planetInsertQuery = `
            INSERT INTO planets (
                local_uuid, planet_name, galaxy, system, position, 
                temp_min, temp_max, diameter, fields_built, fields_explored, fields_max,
                pop_idle, pop_injured, res_food_base
            ) VALUES (
                $1, $2, $3, $4, $5, 
                $6, $7, $8, 0, 10, $9,
                $10, $11, $12
            )
        `;
        await client.query(planetInsertQuery, [
            local_uuid, 
            planetName, 
            galaxy, 
            system, 
            position,
            planetStats.temp_min, 
            planetStats.temp_max, 
            planetStats.diameter, 
            planetStats.fields_max,
            planetStats.pop_idle, 
            planetStats.pop_injured, 
            planetStats.res_food_base
        ]);

        await client.query('COMMIT');

        return { local_uuid, triggerSectorClose };

    } catch (error) {
        await client.query('ROLLBACK');
        console.error('[AccountService] Fehler bei der Account-Erstellung. Transaktion abgebrochen:', error);
        throw error;
    } finally {
        client.release();
    }
};