import { Injectable } from "@nestjs/common"
import { TransactionRepository } from "./repository/transaction.repository"
import { AuthService } from "../auth/auth.service"
import { successResponse, failureResponse } from "src/common/response/response"
import { code } from "src/common/response/response.code"
import {
  successMessage,
  errorMessage,
  validationMessage,
  isEmpty,
} from "src/utils/helpers"
import { messageKey } from "src/constants/message-keys"

@Injectable()
export class TransactionService {
  constructor(
    private readonly transactionRepository: TransactionRepository,
    private readonly authService: AuthService,
  ) {}

  async findAll(token: string) {
    try {
      const loggedInUser: any = await this.authService.getUserByToken(token)
      if (isEmpty(loggedInUser)) {
        return failureResponse(
          code.VALIDATION,
          validationMessage(messageKey.user_not_found),
        )
      }

      const transactions: any = await this.transactionRepository.getByParams({
        where: { user_id: loggedInUser.user_id },
        orderBy: { created_at: "DESC" },
      })

      return successResponse(
        code.SUCCESS,
        successMessage(messageKey.data_retrieve, {
          ":data": "Transaction",
        }),
        transactions,
      )
    } catch (err) {
      return failureResponse(
        code.ERROR,
        errorMessage(messageKey.exception, { ":data": "Transaction" }),
      )
    }
  }
}
