/**
 * API responder for SPA requests 
 * (c)2025 Baxxon
 */

import fs from "node:fs";
import path from "node:path";
import log from "baxxon/logger";
import TextDB from "baxxon/textdb";


export default async function(bx){

    // Parse request params
    const reqAction = bx.reqURL.searchParams.get('action');
    const reqBody = bx.server.req.body || {}; // expected JSON payload
	
	// Force rootPath to be relative to the current site
    const dbOp = { ...reqBody.db };
    dbOp.rootPath = path.join(bx.paths.site, 'data');

	// TextDB instance needs same options as MVC
    const db = new TextDB(dbOp); 
    await db.setData(); // load records into memory

	// Response
    let resPayload = {};

    // Handle request actions
    switch(reqAction){

		case 'reset':
			await resetTestData(db);
			resPayload = {success: true, data: db.getData()};
			break;

        default: // Unknown action
            resPayload = {success: false, err: "Invalid API action"};
            break;
    }

	//log.note( "Response payload", resPayload);

    bx.render.JSON(resPayload);
};

async function resetTestData(db){

	// Clear memory first
	db.clear();

	// delete all data from filesystem
	const dbPath = db.getRootPath();
	const projectRoot = path.resolve( "." );

	// safety check: prevent broad or root deletion
	if( dbPath === projectRoot || dbPath.length < projectRoot.length + 5 ){
		log.error( "ABORT RESET: Safety check failed - invalid or broad path:", dbPath );
		return;
	}

	log.note( "Reseting data for test at:", dbPath );
	fs.rmSync( dbPath, { recursive: true, force: true });
	fs.mkdirSync( dbPath );

	// create test records
	const dir = "test";

	db.addRecord(dir,{ name:"apple", type:"spartan", color:"red", size:"medium", shape:"round" });
	db.addRecord(dir,{ name:"apple", type:"fuji", color:"red", size:"medium", shape:"round" });
	db.addRecord(dir,{ name:"apple", type:"macintosh", color:"red", size:"medium", shape:"round" });
	db.addRecord(dir,{ name:"apple", type:"honey crisp", color:"red", size:"medium", shape:"round" });
	db.addRecord(dir,{ name:"apple", type:"crab", color:"red", size:"small", shape:"round" });
	
	db.addRecord(dir,{ name:"pear", type:"bosc", color:"green", size:"medium", shape:"round" });
	db.addRecord(dir,{ name: "pear", type:"bartlet", color: "green", size: "medium", shape: "round" });
	
	db.addRecord(dir,{ name: "orange", type:"mandarin", color: "orange", size: "medium", shape: "round", });

	db.addRecord(dir,{ name: "banana", type:"organic", color: "yellow", size: "medium", shape: "long", });
	
	db.addRecord(dir,{ name: "grape", type:"concord", color: "purple", size: "small", shape: "round", });
	db.addRecord(dir,{ name: "grape", type:"pinot blanc", color: "green", size: "small", shape: "round", });

	db.addRecord(dir,{ name: "tomato", type:"beef steak", color: "red", size: "large", shape: "round", });

	await db.write();
}


