import { Request, Response, NextFunction } from 'express'
import { categoriesService } from './categories.service'
import { AuthRequest } from '@/shared/middleware/auth'

export class CategoriesController {
  // Get all categories
  async findAll(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const categories = await categoriesService.findAll()
      res.json({
        success: true,
        data: categories
      })
    } catch (error) {
      next(error)
    }
  }

  // Get category tree
  async getTree(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const tree = await categoriesService.getTree()
      res.json({
        success: true,
        data: tree
      })
    } catch (error) {
      next(error)
    }
  }

  // Get category by ID
  async findById(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { id } = req.params
      const category = await categoriesService.findById(id)
      res.json({
        success: true,
        data: category
      })
    } catch (error) {
      next(error)
    }
  }

  // Create category
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const data = req.body
      const category = await categoriesService.create(data)
      res.status(201).json({
        success: true,
        message: 'Category created successfully',
        data: category
      })
    } catch (error) {
      next(error)
    }
  }

  // Update category
  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { id } = req.params
      const data = req.body
      const category = await categoriesService.update(id, data)
      res.json({
        success: true,
        message: 'Category updated successfully',
        data: category
      })
    } catch (error) {
      next(error)
    }
  }

  // Delete category
  async delete(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { id } = req.params
      const result = await categoriesService.delete(id)
      res.json({
        success: true,
        message: 'Category deleted successfully',
        data: result
      })
    } catch (error) {
      next(error)
    }
  }
}

export const categoriesController = new CategoriesController()
