import type { DataSource } from 'typeorm';

import { Company } from '@core/identity/domain/entities/Company';
import type { CompanyRepository } from '@core/identity/domain/repositories/CompanyRepository';

import { CompanyOrmEntity } from '../entities/CompanyOrmEntity';
import { CompanyOrmMapper } from '../mappers/CompanyOrmMapper';

export class TypeOrmCompanyRepository implements CompanyRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: CompanyOrmMapper,
  ) {}

  create(company: Pick<Company, 'getName' | 'getOwnerUserId' | 'getContactEmail'>): Company {
    // Create a new Company instance with generated ID
    const contactEmail = company.getContactEmail();
    return Company.create({
      name: company.getName(),
      ownerUserId: company.getOwnerUserId(),
      ...(contactEmail !== undefined ? { contactEmail } : {}),
    });
  }

  async save(company: Company): Promise<void> {
    const repo = this.dataSource.getRepository(CompanyOrmEntity);
    const entity = this.mapper.toPersistence(company);
    await repo.save(entity);
  }

  async delete(id: string): Promise<void> {
    const repo = this.dataSource.getRepository(CompanyOrmEntity);
    await repo.delete(id);
  }

  async findById(id: string): Promise<Company | null> {
    const repo = this.dataSource.getRepository(CompanyOrmEntity);
    const entity = await repo.findOne({ where: { id } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async findByOwnerUserId(userId: string): Promise<Company | null> {
    const repo = this.dataSource.getRepository(CompanyOrmEntity);
    const entity = await repo.findOne({ where: { ownerUserId: userId } });
    return entity ? this.mapper.toDomain(entity) : null;
  }
}