import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MerchantLocation } from './location.entity';
import { Repository } from 'typeorm';

@Injectable()
export class LocationService {
  constructor(
    @InjectRepository(MerchantLocation)
    private merchantLocationRepo: Repository<MerchantLocation>,
  ) {}

  async getAll(): Promise<MerchantLocation[]> {
    const data = await this.merchantLocationRepo.find();

    return data;
  }

  async getById(id: number): Promise<MerchantLocation> {
    return await this.merchantLocationRepo.findOneBy({
      idMerchant_Location: id,
    });
  }

  async createMerchantLocation(body: any): Promise<any> {
    const location = this.merchantLocationRepo.create(body); //converts plain body object into a proper TypeORM entity
    const data = await this.merchantLocationRepo.save(location);
    return {
      data: data,
      message: 'Location creation completed!',
    };
  }

  async updateMerchantLocation(id: number, body: any): Promise<any> {
    const existing = await this.merchantLocationRepo.findOneBy({
      idMerchant_Location: id,
    });

    if (!existing) {
      throw new Error('Location not found');
    }

    const updated = Object.assign(existing, body); // merge new data into existing
    const saved = await this.merchantLocationRepo.save(updated);

    return {
      data: saved,
      message: 'Location updated successfully!',
    };
  }
}
