import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { CreateTenantDto } from './dto/create-tenant.dto';
import { UpdateTenantDto } from './dto/update-tenant.dto';
import { Tenant } from './entities/tenant.entity';
import { UsersService } from '../users/users.service';

@Injectable()
export class TenantsService {
  constructor(
    @InjectRepository(Tenant)
    private readonly tenantsRepository: Repository<Tenant>,
    private readonly usersService: UsersService,
  ) {}

  findAll() {
    return this.tenantsRepository.find({ order: { createdAt: 'DESC' } });
  }

  async findOne(id: string) {
    const tenant = await this.tenantsRepository.findOne({ where: { id } });
    if (!tenant) throw new NotFoundException('Tenant not found');
    return tenant;
  }

  async create(dto: CreateTenantDto) {
    const exists = await this.tenantsRepository.findOne({
      where: [{ slug: dto.slug }, { name: dto.name }],
    });
    if (exists) throw new ConflictException('Tenant name or slug already exists');

    const tenant = await this.tenantsRepository.save(
      this.tenantsRepository.create(dto),
    );

    const ownerPassword = await bcrypt.hash('123456', 10);

    const owner = await this.usersService.create({
      username: `${dto.slug}_owner`,
      email: `owner@${dto.slug}.local`,
      password: ownerPassword,
      role: 'TENANT_OWNER',
      rank: 'Owner',
      tenantId: tenant.id,
      isActive: true,
    });

    return {
      tenant,
      owner: {
        id: owner.id,
        username: owner.username,
        email: owner.email,
        role: owner.role,
        rank: owner.rank,
      },
    };
  }

  async update(id: string, dto: UpdateTenantDto) {
    const tenant = await this.findOne(id);
    Object.assign(tenant, dto);
    return this.tenantsRepository.save(tenant);
  }

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