import Talhao from '#models/talhao'
import { HttpContext } from '@adonisjs/core/http'

export default class TalhoesController {
  async index({ request, response }: HttpContext) {
    const page = request.input('page', 1)
    const limit = request.input('limit', 10)
    const search = request.input('search', '')

    const query = Talhao.query()

    if (search) {
      query.where((builder) => {
        builder.where('nome', 'ILIKE', `%${search}%`).orWhere('codigo', 'ILIKE', `%${search}%`)
      })
    }

    const talhoes = await query.paginate(page, limit)
    return response.ok(talhoes)
  }

  async store({ request, response }: HttpContext) {
    const data = request.only([
      'codigo',
      'nome',
      'area_hectares',
      'cultura',
      'localizacao',
      'is_ativo',
    ])

    try {
      const talhao = await Talhao.create(data)
      return response.created(talhao)
    } catch (error) {
      return response.badRequest({ message: 'Failed to create talhao', error: error.message })
    }
  }

  async show({ params, response }: HttpContext) {
    try {
      const talhao = await Talhao.findOrFail(params.id)
      return response.ok(talhao)
    } catch (error) {
      return response.notFound({ message: 'Talhao not found' })
    }
  }

  async update({ params, request, response }: HttpContext) {
    try {
      const talhao = await Talhao.findOrFail(params.id)
      const data = request.only([
        'codigo',
        'nome',
        'area_hectares',
        'cultura',
        'localizacao',
        'is_ativo',
      ])

      talhao.merge(data)
      await talhao.save()

      return response.ok(talhao)
    } catch (error) {
      return response.badRequest({ message: 'Failed to update talhao', error: error.message })
    }
  }

  async destroy({ params, response }: HttpContext) {
    try {
      const talhao = await Talhao.findOrFail(params.id)
      await talhao.delete()

      return response.ok({ message: 'Talhao deleted successfully' })
    } catch (error) {
      return response.badRequest({ message: 'Failed to delete talhao', error: error.message })
    }
  }
}
