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

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

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

        //Load all Customers
        [HttpGet]
        public async Task<ActionResult<IEnumerable<CustomerModel>>> GetCustomers()
        {
            return await _context.Customers.ToListAsync();
        }


        //Load single Customer
        [HttpGet("{id}")]
        public async Task<ActionResult<CustomerModel>> GetCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
                return NotFound();

            return customer;
        }

        //Create Customer
        [HttpPost]
        public async Task<ActionResult<CustomerModel>> PostCustomer(CustomerModel customer)
        {
            _context.Customers.Add(customer);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
        }


        //Delete Customer
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
                return NotFound();

            _context.Customers.Remove(customer);
            await _context.SaveChangesAsync();
            return NoContent();
        }

        //PUT Customer
        [HttpPut("{id}")]
        public async Task<IActionResult> PutCustomer(int id, CustomerModel customer)
        {
            if (id != customer.Id)
                return BadRequest();

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

            existing.Name = customer.Name;
            existing.Standort = customer.Standort;
            existing.Ansprechpartner = customer.Ansprechpartner;
            existing.Email = customer.Email;
            existing.Telefon = customer.Telefon;

            _context.Entry(existing).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Customers.Any(c => c.Id == id))
                    return NotFound();
                else
                    throw;
            }

            return NoContent();
        }
    }
}
