import { BadRequestException, Injectable } from '@nestjs/common';
import { RoleCode } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { UsersService } from '../users/users.service';
import { CreateResidentDto } from './dto/create-resident.dto';

@Injectable()
export class ResidentsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly usersService: UsersService,
  ) {}

  async create(tenantId: string, dto: CreateResidentDto) {
    const lot = await this.prisma.lot.findUnique({ where: { id: dto.lotId } });
    if (!lot) throw new BadRequestException('Lot not found');

    // find or create user
    let user = await this.prisma.user.findUnique({ where: { email: dto.email } });
    if (!user) {
      const tempPassword = dto.password ?? Math.random().toString(36).slice(2, 12);
      const roleCode: RoleCode = dto.role === 'LOCATAIRE' ? 'LOCATAIRE' : 'COPROPRIETAIRE';
      user = await this.usersService.createWithRole({
        email: dto.email,
        password: tempPassword,
        firstName: dto.firstName,
        lastName: dto.lastName,
        phone: dto.phone,
        roleCode,
        tenantId,
      });
    }

    return this.prisma.resident.create({
      data: {
        userId: user.id,
        lotId: dto.lotId,
        role: dto.role,
        isPrimary: dto.isPrimary ?? true,
      },
      include: { user: true, lot: true },
    });
  }

  findByLot(lotId: string) {
    return this.prisma.resident.findMany({
      where: { lotId },
      include: { user: true },
    });
  }

  async endResidency(id: string) {
    return this.prisma.resident.update({
      where: { id },
      data: { endDate: new Date() },
    });
  }
}
