src/services/systems.service.tsadded
import { LoggerFactory } from "../util/logger";
import { query } from "../db/db";
import { NotFoundError } from "../types/errortypes";
import { getLoggedInUsername } from "../util/username";
import { PagingQueryParam } from "../models/ingress";
import { IndexedItem } from "../util/pagination.util";

const logger = LoggerFactory("SystemsService");

const SQL = {
    LIST: `SELECT * FROM xyz."fn_GetCommissioningSystemList"($1, $2, $3)`,
    GET_BY_ID: `SELECT * FROM xyz."fn_GetCommissioningSystem"($1, $2)`,
    INSERT: `SELECT * FROM xyz."fn_InsertCommissioningSystem"($1, $2, $3, $4)`,
};

export interface CommissioningSystem {
    commissioningSystemId: string;
    name: string;
    systemTypeId: string;
    createdBy: string;
    insertedOn: Date;
    lastModifiedOn: Date | null;
    lastModifiedBy: string | null;
}

function mapRow(row: any): CommissioningSystem {
    return {
        commissioningSystemId: row.CommissioningSystemId,
        name: row.Name,
        systemTypeId: row.SystemTypeId,
        createdBy: row.CreatedBy,
        insertedOn: row.InsertedOn,
        lastModifiedOn: row.LastModifiedOn ?? null,
        lastModifiedBy: row.LastModifiedBy ?? null,
    };
}

function mapError(err: unknown): never {
    if (err instanceof Error && err.message.includes("SystemType with id")) {
        throw new NotFoundError(err.message);
    }
    throw err;
}

export async function listCommissioningSystems(projectId: string, paging: PagingQueryParam): Promise<(CommissioningSystem & IndexedItem)[]> {
    try {
        const { rows } = await query(SQL.LIST, [projectId, paging.lastFetchedIndexId, paging.size]);
        return rows.map((row: any) => ({ ...mapRow(row), indexId: row.Id }));
    } catch (err) {
        logger.error("Error while listing commissioning systems", err);
        throw err;
    }
}

export async function getCommissioningSystemById(projectId: string, commissioningSystemId: string): Promise<CommissioningSystem> {
    try {
        const { rows } = await query(SQL.GET_BY_ID, [projectId, commissioningSystemId]);
        if (rows.length === 0) {
            throw new NotFoundError(`CommissioningSystem with id: ${commissioningSystemId} not found.`);
        }
        return mapRow(rows[0]);
    } catch (err) {
        logger.error("Error while fetching commissioning system", err);
        throw err;
    }
}

export async function createCommissioningSystem(projectId: string, systemTypeId: string, name: string): Promise<CommissioningSystem> {
    try {
        const { rows } = await query(SQL.INSERT, [projectId, systemTypeId, name, getLoggedInUsername()]);
        return mapRow(rows[0]);
    } catch (err) {
        logger.error("Error while creating commissioning system", err);
        mapError(err);
    }
}