using FilterCair.Server.Data;
using FilterCair.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace FilterCair.Server.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FilterController : ControllerBase
    {
        private readonly FilterCairContext _context;

        public FilterController(FilterCairContext context)
        {
            _context = context;
        }

        [HttpGet("byStation/{stationId}")]
        public async Task<ActionResult<IEnumerable<FilterModel>>> GetFiltersByStation(int stationId)
        {
            return await _context.Filters
                .Where(f => f.StationId == stationId).ToListAsync();
                
        }

        [HttpPost]
        public async Task<IActionResult> CreateFilter(FilterModel filter)
        {
            _context.Filters.Add(filter);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetFiltersByStation), new { stationId = filter.StationId }, filter);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<FilterModel>> GetFilterById(int id)
        {
            var filter = await _context.Filters.FindAsync(id);
            if (filter == null)
                return NotFound();

            return filter;
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateFilter(int id, FilterModel updatedFilter)
        {
            if (id != updatedFilter.Id)
                return BadRequest("ID stimmt nicht überein.");

            var existing = await _context.Filters.FindAsync(id);
            if (existing == null)
                return NotFound();

            // Werte übernehmen
            existing.Bezeichnung = updatedFilter.Bezeichnung;
            existing.Typ = updatedFilter.Typ;
            existing.Seriennummer = updatedFilter.Seriennummer;
            existing.Einbaudatum = updatedFilter.Einbaudatum;
            existing.LetzteWartung = updatedFilter.LetzteWartung;
            existing.Zustand = updatedFilter.Zustand;
            existing.QRCode = updatedFilter.QRCode;

            await _context.SaveChangesAsync();
            return NoContent();
        }

    }

}
