const db = require('../models');

module.exports = class Claim_requestsDBApi {
  static async create(data, { currentUser, transaction }) {
    const claim_request = await db.claim_requests.create(
      {
        businessId: data.businessId,
        userId: data.userId,
        status: data.status || 'PENDING',
        createdById: currentUser?.id,
      },
      { transaction },
    );
    return claim_request;
  }

  static async update(id, data, { currentUser, transaction }) {
    const claim_request = await db.claim_requests.findByPk(id, { transaction });
    if (!claim_request) throw new Error('Claim request not found');
    
    await claim_request.update(
      {
        ...data,
        updatedById: currentUser?.id,
      },
      { transaction },
    );
    return claim_request;
  }

  static async findBy(where, options = {}) {
    return await db.claim_requests.findOne({
      where,
      include: [
        { model: db.businesses, as: 'business' },
        { model: db.users, as: 'user' },
      ],
      ...options,
    });
  }

  static async findAll(query = {}, { currentUser } = {}) {
    const { limit, offset, filter } = query;
    const where = {};
    
    // Support direct query params
    if (query.userId) where.userId = query.userId;
    if (query.status) where.status = query.status;
    if (query.businessId) where.businessId = query.businessId;

    if (filter) {
        // Support filter object if provided
        if (filter.userId) where.userId = filter.userId;
        if (filter.status) where.status = filter.status;
        if (filter.businessId) where.businessId = filter.businessId;
    }

    const { rows, count } = await db.claim_requests.findAndCountAll({
      where,
      include: [
        { model: db.businesses, as: 'business' },
        { model: db.users, as: 'user' },
      ],
      limit: limit ? parseInt(limit) : undefined,
      offset: offset ? parseInt(offset) : undefined,
      order: [['createdAt', 'DESC']],
    });
    return { rows, count };
  }
};