import { Injectable } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { ApplicationFile } from '../../database/tenant/entities/application-file.entity';

@Injectable()
export class ApplicationFilesService {
  constructor(private tenantConn: TenantConnectionService) {}

  private async repo(sub: string) {
    const ds = await this.tenantConn.getTenantDataSource(sub);
    return ds.getRepository(ApplicationFile);
  }

  async getByApplication(sub: string, applicationId: string) {
    const r = await this.repo(sub);
    return r.findOne({ where: { applicationId } });
  }

  async upsert(sub: string, applicationId: string, dto: Partial<ApplicationFile>) {
    const r = await this.repo(sub);
    const existing = await r.findOne({ where: { applicationId } });
    if (existing) {
      await r.update(existing.id, { ...dto, applicationId });
      return r.findOne({ where: { applicationId } });
    }
    return r.save(r.create({ ...dto, applicationId }));
  }

  async updateField(sub: string, applicationId: string, field: string, filePath: string) {
    const r = await this.repo(sub);
    const existing = await r.findOne({ where: { applicationId } });
    if (existing) {
      await r.update(existing.id, { [field]: filePath });
    } else {
      await r.save(r.create({ applicationId, [field]: filePath }));
    }
    return r.findOne({ where: { applicationId } });
  }
}
