import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Organization } from './entities/organization.entity';
import { CreateOrganizationDto } from './dto/create-organization.dto';
import { UpdateOrganizationDto } from './dto/update-organization.dto';

@Injectable()
export class OrganizationsService {
  constructor(
    @InjectRepository(Organization)
    private readonly organizationsRepository: Repository<Organization>,
  ) {}

  findAll() {
    return this.organizationsRepository.find({
      relations: { tenant: true },
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: string) {
    const organization = await this.organizationsRepository.findOne({
      where: { id },
      relations: { tenant: true },
    });

    if (!organization) {
      throw new NotFoundException('Organization not found');
    }

    return organization;
  }

  async create(dto: CreateOrganizationDto) {
    const exists = await this.organizationsRepository.findOne({
      where: { slug: dto.slug },
    });

    if (exists) {
      throw new ConflictException('Organization slug already exists');
    }

    const organization = this.organizationsRepository.create(dto);
    return this.organizationsRepository.save(organization);
  }

  async update(id: string, dto: UpdateOrganizationDto) {
    const organization = await this.findOne(id);
    Object.assign(organization, dto);
    return this.organizationsRepository.save(organization);
  }

  async remove(id: string) {
    const organization = await this.findOne(id);
    await this.organizationsRepository.remove(organization);
    return { success: true };
  }
}