using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebVentaCoche.DataBase;
using WebVentaCoche.Models;
using WebVentaCoche.ViewModels;

namespace WebVentaCoche.Controllers
{
    [Authorize]
    public class AddressController : Controller
    {
        private readonly ApplicationDbContext _context;

        public AddressController(ApplicationDbContext context)
        {
            _context = context;
        }

        //POST:/Address/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(AddressViewModel input)
        {
            if (!ModelState.IsValid)
                return RedirectToAction("Addresses", "Account");

            var entity = new Address
            {
                Street = input.Street,
                City = input.City,
                State = input.State,
                ZipCode = input.ZipCode,
                Country = input.Country,
                UserId = User.FindFirstValue(ClaimTypes.NameIdentifier)!
            };

            _context.Addresses.Add(entity);
            await _context.SaveChangesAsync();
            return RedirectToAction("Addresses", "Account");
        }

        //POST:/Address/Edit/{id}
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, Address model)
        {
            if (id != model.Id)
                return BadRequest();

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var address = await _context.Addresses.FindAsync(id);

            if (address == null || address.UserId != userId)
                return NotFound();

            address.Street = model.Street;
            address.City = model.City;
            address.State = model.State;
            address.ZipCode = model.ZipCode;
            address.Country = model.Country;

            await _context.SaveChangesAsync();
            return RedirectToAction("Addresses", "Account");
        }

        //POST: /Address/Delete/{id}
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var address = await _context.Addresses.FindAsync(id);
            if (address == null || address.UserId != userId)
                return NotFound();

            _context.Addresses.Remove(address);
            await _context.SaveChangesAsync();
            return RedirectToAction("Addresses", "Account");
        }
    }
}
