using Cloud.Models; using Cloud.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Cloud.Controllers { [Authorize] [ApiController] [Route("api/user")] public class FarmController : ControllerBase { private IConfiguration _config; private ApplicationContext _context; public FarmController(IConfiguration config, ApplicationContext context) { _config = config; _context = context; } [HttpGet("{userId}/farm")] public async Task>> Index(int userId) { try { List farms = await _context.Farms.Where(x => x.UserId == userId).AsNoTracking().ToListAsync(); if (!farms.Any()) return NotFound("Farms is not found"); return Ok(farms); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpGet("{userId}/farm/{farmId}")] public async Task> Show(int userId, int farmId) { try { Farm? farm = await _context.Farms.FirstOrDefaultAsync(x => x.UserId == userId && x.Id == farmId); if (farm == null) return NotFound("Farm is not found"); return Ok(farm); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpPost("{userId}/farm")] public async Task> Create([FromBody] FarmRequest farmRequest, int userId) { try { var farm = new Farm { Name = farmRequest.Name, UserId = userId, RaspberryIP = farmRequest.RaspberryIP, }; Farm? farmCreated = _context.Farms.Add(farm).Entity; await _context.SaveChangesAsync(); return Ok(farmCreated); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpPut("{userId}/farm/{farmId}")] public async Task> Update([FromBody] FarmRequest farmRequest, int userId, int farmId) { try { Farm? farm = await _context.Farms.FirstOrDefaultAsync(x => x.Id == farmId && x.UserId == userId); if (farm == null) return NotFound("Farm is not found"); farm.Name = farmRequest.Name; farm.RaspberryIP = farmRequest.RaspberryIP; _context.Farms.Update(farm); await _context.SaveChangesAsync(); return Ok(farm); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpDelete("{userId}/farm/{farmId}")] public async Task Delete(int userId, int farmId) { try { Farm? farm = await _context.Farms.FirstOrDefaultAsync(x => x.Id == farmId && x.UserId == userId); if (farm == null) return NotFound("Farm is not found"); _context.Farms.Remove(farm); await _context.SaveChangesAsync(); return Ok("Farm deleted successfully"); } catch (Exception ex) { return BadRequest(ex.Message); } } } }