import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { BoardMember } from '../../database/tenant/entities/board-member.entity';
import { Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable()
export class BoardMembersService {
  constructor(
    private tenantConn: TenantConnectionService,
    @Inject(REQUEST) private request: Request,
  ) {}

  private sub() { return (this.request as any).tenantSubdomain as string; }
  private async repo() {
    const ds = await this.tenantConn.getTenantDataSource(this.sub());
    return ds.getRepository(BoardMember);
  }

  async list(q?: string, officeId?: string) {
    const r = await this.repo();
    const qb = r.createQueryBuilder('bm').where('bm.deletedAt IS NULL').orderBy('bm.order', 'ASC').addOrderBy('bm.name');
    if (q) qb.andWhere('(bm.name LIKE :q OR bm.position LIKE :q)', { q: `%${q}%` });
    if (officeId) qb.andWhere('bm.officeId = :officeId', { officeId });
    return qb.getMany();
  }

  async findOne(id: string) {
    const r = await this.repo();
    const e = await r.findOne({ where: { id } });
    if (!e) throw new NotFoundException('Board member not found');
    return e;
  }

  async create(dto: Partial<BoardMember>) {
    const r = await this.repo();
    return r.save(r.create({ ...dto, status: dto.status ?? 'active' }));
  }

  async update(id: string, dto: Partial<BoardMember>) {
    const r = await this.repo();
    const e = await this.findOne(id);
    return r.save(Object.assign(e, dto));
  }

  async remove(id: string) {
    const r = await this.repo();
    await r.softDelete(id);
    return { id };
  }
}
