import { AssetModel, Asset } from "../models/assetModel";
import db from "../db";
import { TEXT_MESSAGES } from "../const";

const assetResolver = {
  Query: {
    getAssetById: async (_: any, { id }: { id: number }) => {
      try {
        const asset = await AssetModel.getAssetById(id);
        if (!asset) {
          throw new Error(TEXT_MESSAGES.ASSET_NOT_FOUND || "Asset not found");
        }
        return asset;
      } catch (error) {
        console.error(TEXT_MESSAGES.ERROR_FETCHING_ASSET_BY_ID, error);
        throw new Error(
          `${TEXT_MESSAGES.ERROR_FETCHING_ASSET_BY_ID}: ${error}`
        );
      }
    },

    getAllAssets: async () => {
      try {
        const assets = await AssetModel.findAllAssets();
        if (!assets || assets.length === 0) {
          return [];
        }

        return assets.map((asset: Asset) => ({
          ...asset,
          numberOfInvestments: asset.numberOfInvestments ?? 0,
        }));
      } catch (error: any) {
        console.error(TEXT_MESSAGES.ERROR_FETCHING_ASSETS, error);
        throw new Error(
          `${TEXT_MESSAGES.ERROR_FETCHING_ASSETS} ${error.message}`
        );
      }
    },
getAssetByPage: async (
  _: any,
  {
    searchQuery = "",
    page = 1,
    perPage = 10,
  }: {
    searchQuery?: string;
    page?: number;
    perPage?: number;
  }
) => {
  try {
    const offset = (page - 1) * perPage;
    const searchCondition = `%${searchQuery}%`;

    const [assets]: any = await db.query(
      `SELECT * FROM assets WHERE market LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?`,
      [searchCondition, perPage, offset]
    );

    const [countRows]: any = await db.query(
      `SELECT COUNT(*) as total FROM assets WHERE market LIKE ?`,
      [searchCondition]
    );

    const total = countRows[0]?.total ?? 0;

    const formattedAssets = await Promise.all(
      assets.map(async (asset: any) => {
        const [products]: any = await db.query(
          `SELECT * FROM asset_products WHERE asset_id = ?`,
          [asset.id]
        );

        return {
          id: asset.id,
          market: asset.market,
          numberOfInvestments: asset.number_of_investments ?? 0,
          benchmark: asset.benchmark,
          inceptionDate: asset.inception_date,
          products: products.map((product: any) => ({
            id: product.id,
            productName: product.product_name,
            productImage: product.product_image,
            description: product.description,
            assetClass: product.asset_class,
            minimumInvestment: product.minimum_investment,
            investorType: product.investor_type,
          })),
        };
      })
    );

    return {
      items: formattedAssets,
      total: total,
      page: page,
      perPage: perPage,
      totalPages: Math.ceil(total / perPage),
    };
  } catch (error: any) {
    console.error(TEXT_MESSAGES.FAILED_TO_FETCH_PAGINATED_ASSETS, error);
    throw new Error(TEXT_MESSAGES.FAILED_TO_FETCH_PAGINATED_ASSETS);
  }
},
  },

  Mutation: {
    createAsset: async (_: any, { input }: any) => {
      try {
        const asset = await AssetModel.createAsset(input);
        return {
          success: true,
          message: TEXT_MESSAGES.ASSET_CREATED_SUCCESSFULLY,
          data: asset,
        };
      } catch (error: any) {
        return {
          success: false,
          message: `${TEXT_MESSAGES.FAILED_TO_CREATE_ASSET} ${error.message}`,
          data: null,
        };
      }
    },
  },
};

export default assetResolver;
