import { Injectable } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { ActivityLog } from '../../database/tenant/entities/activity-log.entity';

@Injectable()
export class ActivityLogsService {
  constructor(private tenantConn: TenantConnectionService) {}
  private async repo(sub: string) {
    const ds = await this.tenantConn.getTenantDataSource(sub);
    return ds.getRepository(ActivityLog);
  }

  async log(sub: string, data: {
    userId?: string; userName?: string;
    action: string; module: string;
    recordId?: string; message?: string;
    oldData?: object; newData?: object;
    ipAddress?: string;
  }) {
    try {
      const r = await this.repo(sub);
      await r.save(r.create({
        userId: data.userId,
        userName: data.userName,
        action: data.action,
        module: data.module,
        recordId: data.recordId,
        message: data.message,
        oldData: data.oldData ? JSON.stringify(data.oldData) : undefined,
        newData: data.newData ? JSON.stringify(data.newData) : undefined,
        ipAddress: data.ipAddress,
      } as any));
    } catch { /* never block main flow */ }
  }

  async findAll(sub: string, opts: { module?: string; action?: string; userId?: string; q?: string; page?: number; limit?: number }) {
    const r = await this.repo(sub);
    const { module: mod, action, userId, q, page = 1, limit = 30 } = opts;
    const qb = r.createQueryBuilder('a')
      .orderBy('a.createdAt', 'DESC')
      .skip((page - 1) * limit)
      .take(limit);
    if (mod) qb.andWhere('a.module = :mod', { mod });
    if (action) qb.andWhere('a.action = :action', { action });
    if (userId) qb.andWhere('a.userId = :userId', { userId });
    if (q) qb.andWhere('(a.userName LIKE :q OR a.message LIKE :q OR a.module LIKE :q)', { q: `%${q}%` });
    const [items, total] = await qb.getManyAndCount();
    return { items, total, page, limit };
  }
}
