/* eslint-disable @typescript-eslint/no-shadow */
import {
  Count,
  CountSchema,
  Filter,
  FilterExcludingWhere,
  repository,
  Where,
} from '@loopback/repository';

import {
  del,
  get,
  getModelSchemaRef,
  param,
  patch,
  post,
  put,
  requestBody,
  response,
  RestBindings,
  Request,
} from '@loopback/rest';

import {inject} from '@loopback/core';
import fs from 'fs';
import multer from 'multer';
import path from 'path';
import {BackgroundImageMaster} from '../models';
import {BackgroundImageMasterRepository} from '../repositories';

// Upload directory path
const uploadDir = path.resolve(__dirname, '../../uploads/Slider-Photo');
fs.mkdirSync(uploadDir, {recursive: true});

// Multer storage config
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, uploadDir);
  },
  filename(req, file, cb) {
    const uniqueName = `${Date.now()}-${Math.round(
      Math.random() * 1e9,
    )}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  },
});

const upload = multer({storage});

export class BackgroundimagemasterController {
  constructor(
    @inject(RestBindings.Http.REQUEST) private request: Request,
    @repository(BackgroundImageMasterRepository)
    public backgroundImageMasterRepository: BackgroundImageMasterRepository,
  ) {}

  // CREATE with file upload
@post('/background-image-masters')
@response(200, {
  description: 'BackgroundImageMaster model instance',
  content: {'application/json': {schema: getModelSchemaRef(BackgroundImageMaster)}},
})
async create(): Promise<BackgroundImageMaster> {
  const req = this.request as any;

  const uploaded = await new Promise<Express.Multer.File[]>((resolve, reject) => {
    upload.single('backImage')(req, {} as any, (err: any) => {
      if (err) return reject(err);
      resolve(req.file ? [req.file] : []);
    });
  });

  const file = uploaded[0];
  const body = req.body;

  const newData = {
    ...body,
    backImage: file ? file.filename : '',
  };

  return this.backgroundImageMasterRepository.create(newData);
}



  // COUNT
  @get('/background-image-masters/count')
  @response(200, {
    description: 'BackgroundImageMaster model count',
    content: {'application/json': {schema: CountSchema}},
  })
  async count(
    @param.where(BackgroundImageMaster) where?: Where<BackgroundImageMaster>,
  ): Promise<Count> {
    return this.backgroundImageMasterRepository.count(where);
  }

  // FIND
  @get('/background-image-masters')
  @response(200, {
    description: 'Array of BackgroundImageMaster model instances',
    content: {
      'application/json': {
        schema: {
          type: 'array',
          items: getModelSchemaRef(BackgroundImageMaster, {
            includeRelations: true,
          }),
        },
      },
    },
  })
  async find(
    @param.filter(BackgroundImageMaster) filter?: Filter<BackgroundImageMaster>,
  ): Promise<BackgroundImageMaster[]> {
    return this.backgroundImageMasterRepository.find(filter);
  }

  // FIND BY ID
  @get('/background-image-masters/{id}')
  @response(200, {
    description: 'BackgroundImageMaster model instance',
    content: {
      'application/json': {
        schema: getModelSchemaRef(BackgroundImageMaster, {
          includeRelations: true,
        }),
      },
    },
  })
  async findById(
    @param.path.number('id') id: number,
    @param.filter(BackgroundImageMaster, {exclude: 'where'})
    filter?: FilterExcludingWhere<BackgroundImageMaster>,
  ): Promise<BackgroundImageMaster> {
    return this.backgroundImageMasterRepository.findById(id, filter);
  }

  // PATCH by id with file upload
  @patch('/background-image-masters/{id}')
  @response(204, {description: 'BackgroundImageMaster PATCH success'})
  async updateById(@param.path.number('id') id: number): Promise<void> {
    const req = this.request as any;

    const uploaded = await new Promise<Express.Multer.File[]>((resolve, reject) => {
      upload.single('backImage')(req, {} as any, (err: any) => {
        if (err) return reject(err);
        resolve(req.file ? [req.file] : []);
      });
    });

    const file = uploaded[0];
    const body = req.body;

    const updatedBackground = {
      ...body,
      ...(file ? {backImage: file.filename} : {}),
    };

    await this.backgroundImageMasterRepository.updateById(id, updatedBackground);
  }

  // PUT by id (replace) with file upload
  @put('/background-image-masters/{id}')
  @response(204, {description: 'BackgroundImageMaster PUT success'})
  async replaceById(@param.path.number('id') id: number): Promise<void> {
    const req = this.request as any;

    const uploaded = await new Promise<Express.Multer.File[]>((resolve, reject) => {
      upload.single('backImage')(req, {} as any, (err: any) => {
        if (err) return reject(err);
        resolve(req.file ? [req.file] : []);
      });
    });

    const file = uploaded[0];
    const body = req.body;

    const replacedBackground = {
      ...body,
      backImage: file ? file.filename : '',
    };

    await this.backgroundImageMasterRepository.replaceById(id, replacedBackground);
  }

  // PATCH multiple records
  @patch('/background-image-masters')
  @response(200, {
    description: 'BackgroundImageMaster PATCH success count',
    content: {'application/json': {schema: CountSchema}},
  })
  async updateAll(
    @requestBody({
      description: 'multipart/form-data request',
      required: true,
      content: {
        'application/json': {
          schema: getModelSchemaRef(BackgroundImageMaster, {partial: true}),
        },
      },
    })
    backgroundImageMaster: BackgroundImageMaster,
    @param.where(BackgroundImageMaster) where?: Where<BackgroundImageMaster>,
  ): Promise<Count> {
    return this.backgroundImageMasterRepository.updateAll(
      backgroundImageMaster,
      where,
    );
  }

  // DELETE by id
  @del('/background-image-masters/{id}')
  @response(204, {description: 'BackgroundImageMaster DELETE success'})
  async deleteById(@param.path.number('id') id: number): Promise<void> {
    await this.backgroundImageMasterRepository.deleteById(id);
  }
}
