src/services/asset.types.service.tsadded
import { LoggerFactory } from "../util/logger";
import { query } from "../db/db";
import { DB_ConstraintViolationError, NotFoundError, ResourceConflictError } from "../types/errortypes";
import { getLoggedInUsername } from "../util/username";

const logger = LoggerFactory("AssetTypesService");

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

export interface AssetType {
    assetTypeId: string;
    name: string;
    code: string;
    createdBy: string;
    insertedOn: Date;
    lastModifiedOn: Date | null;
    lastModifiedBy: string | null;
}

function mapRow(row: any): AssetType {
    return {
        assetTypeId: row.AssetTypeId,
        name: row.Name,
        code: row.Code,
        createdBy: row.CreatedBy,
        insertedOn: row.InsertedOn,
        lastModifiedOn: row.LastModifiedOn ?? null,
        lastModifiedBy: row.LastModifiedBy ?? null,
    };
}

function mapError(err: unknown, name?: string, code?: string): never {
    if (err instanceof DB_ConstraintViolationError && err.message.includes("AssetType_ProjectShardId_Name_key")) {
        throw new ResourceConflictError(`An asset type named '${name}' already exists in this project.`);
    }
    if (err instanceof DB_ConstraintViolationError && err.message.includes("AssetType_ProjectShardId_Code_key")) {
        throw new ResourceConflictError(`An asset type with code '${code}' already exists in this project.`);
    }
    throw err;
}

export async function listAssetTypes(projectId: string): Promise<AssetType[]> {
    try {
        const { rows } = await query(SQL.LIST, [projectId]);
        return rows.map(mapRow);
    } catch (err) {
        logger.error("Error while listing asset types", err);
        throw err;
    }
}

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

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