import {
    ConflictException,
    Injectable,
    NotFoundException,
  } from '@nestjs/common';
  import { TenantConnectionService } from '../../database/tenant-connection.service';
  import { requireCurrentTenant } from '../../database/tenant-context';
  import { Office } from '../../database/tenant/entities/office.entity';
  import { Branch } from '../../database/tenant/entities/branch.entity';
  import { CreateOfficeDto, UpdateOfficeDto } from './dto/create-office.dto';

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

    private async ds() {
      const ctx = requireCurrentTenant();
      return this.tenantConn.getTenantDataSource(ctx.subdomain);
    }

    async list() {
      const ds = await this.ds();
      return ds.getRepository(Office).find({
        relations: { parentOffice: true, branches: true },
        order: { code: 'ASC' },
      });
    }

    async getOne(id: string) {
      const ds = await this.ds();
      const o = await ds.getRepository(Office).findOne({
        where: { id },
        relations: { parentOffice: true, branches: true },
      });
      if (!o) throw new NotFoundException('Office not found');
      return o;
    }

    async create(dto: CreateOfficeDto) {
      const ds = await this.ds();
      const repo = ds.getRepository(Office);
      const exists = await repo.findOne({ where: { code: dto.code } });
      if (exists) throw new ConflictException('Office code already exists');
      const office = await repo.save(
        repo.create({ ...dto, active: dto.active ?? true }),
      );
      return this.getOne(office.id);
    }

    async update(id: string, dto: UpdateOfficeDto) {
      const ds = await this.ds();
      const repo = ds.getRepository(Office);
      const o = await repo.findOne({ where: { id } });
      if (!o) throw new NotFoundException('Office not found');
      Object.assign(o, dto);
      await repo.save(o);
      return this.getOne(id);
    }

    async remove(id: string) {
      const ds = await this.ds();
      const branches = await ds.getRepository(Branch).count({
        where: { officeId: id },
      });
      if (branches > 0) {
        throw new ConflictException('Office has branches; remove them first');
      }
      await ds.getRepository(Office).delete(id);
      return { ok: true };
    }
  }
  