import { Injectable, Logger } from '@nestjs/common';
import { YachtsService } from '../yachts/yachts.service';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);

  private readonly users: User[] = [
    {
      userId: 1,
      firstName: 'Иван',
      lastName: 'Андреев',
      phone: '+79009009090',
      email: 'ivan@yachting.ru',
      password: 'admin',
      companyName: 'Северный Флот',
      inn: 1234567890,
      ogrn: 1122334455667,
    },
    {
      userId: 2,
      firstName: 'Сергей',
      lastName: 'Большаков',
      phone: '+79119119191',
      email: 'sergey@yachting.ru',
      password: 'admin',
      companyName: 'Балтийские Просторы',
      inn: 9876543210,
      ogrn: 9988776655443,
    },
    {
      userId: 3,
      firstName: 'Анна',
      lastName: 'Петрова',
      phone: '+79229229292',
      email: 'anna@yachting.ru',
      password: 'admin',
      companyName: 'Ладожские Ветры',
      inn: 5555555555,
      ogrn: 3333444455556,
    },
    {
      userId: 4,
      firstName: 'Дмитрий',
      lastName: 'Соколов',
      phone: '+79339339393',
      email: 'dmitry@yachting.ru',
      password: 'admin',
      companyName: 'Финский Залив',
      inn: 1111222233,
      ogrn: 7777888899990,
    },
  ];

  async findOne(
    email: string,
    includeYachts: boolean = false,
  ): Promise<User | undefined> {
    const user = this.users.find((user) => user.email === email);

    if (user && includeYachts) {
      user.yachts = [];
    }

    return user;
  }

  async findByPhone(
    phone: string,
    includeYachts: boolean = false,
  ): Promise<User | undefined> {
    const user = this.users.find((u) => u.phone === phone);
    if (user && includeYachts) {
      user.yachts = [];
    }
    return user;
  }

  /** Создать пользователя по номеру телефона (при первой авторизации по коду). */
  async createByPhone(phone: string): Promise<User> {
    const maxId = this.users.length
      ? Math.max(...this.users.map((u) => u.userId))
      : 0;
    const newUser: User = {
      userId: maxId + 1,
      firstName: '',
      lastName: '',
      phone,
      email: '',
      yachts: [],
    };
    this.users.push(newUser);
    return newUser;
  }

  async findById(
    userId: number,
    includeYachts: boolean = false,
  ): Promise<User | undefined> {
    const user = this.users.find((user) => user.userId === userId);

    if (user && includeYachts) {
      user.yachts = [];
    }

    return user;
  }

  async findAll(includeYachts: boolean = false): Promise<User[]> {
    if (!includeYachts) {
      return this.users;
    }

    const usersWithYachts = await Promise.all(
      this.users.map(async (user) => {
        const yachts = [];
        return { ...user, yachts };
      }),
    );

    return usersWithYachts;
  }
}
