import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Workspace } from './entities/workspace.entity';
import { CreateWorkspaceDto } from './dto/create-workspace.dto';
import { UpdateWorkspaceDto } from './dto/update-workspace.dto';

@Injectable()
export class WorkspacesService {
  constructor(
    @InjectRepository(Workspace)
    private readonly workspacesRepository: Repository<Workspace>,
  ) {}

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

  async findOne(id: string) {
    const workspace = await this.workspacesRepository.findOne({
      where: { id },
      relations: { tenant: true, organization: true },
    });
    if (!workspace) throw new NotFoundException('Workspace not found');
    return workspace;
  }

  async create(dto: CreateWorkspaceDto) {
    const exists = await this.workspacesRepository.findOne({
      where: { slug: dto.slug },
    });
    if (exists) throw new ConflictException('Workspace slug already exists');
    const workspace = this.workspacesRepository.create(dto);
    return this.workspacesRepository.save(workspace);
  }

  async update(id: string, dto: UpdateWorkspaceDto) {
    const workspace = await this.findOne(id);
    Object.assign(workspace, dto);
    return this.workspacesRepository.save(workspace);
  }

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