package com.example.springip.lab3.controller;

import com.example.springip.WebConfiguration;
import com.example.springip.lab3.dto.CompanyDto;
import com.example.springip.lab3.dto.EmployeeDto;
import com.example.springip.lab3.models.Employee;
import com.example.springip.lab3.service.CompanyService;
import com.example.springip.lab3.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(WebConfiguration.REST_API + "/company")
public class CompanyController {
    private final CompanyService companyService;
    private final EmployeeService employeeService;

    public CompanyController(CompanyService companyService, EmployeeService employeeService) {
        this.companyService = companyService;
        this.employeeService = employeeService;
    }

    @GetMapping("/{id}")
    public CompanyDto getCompany(@PathVariable long id) {
        return new CompanyDto(companyService.findCompany(id));
    }

    @GetMapping("/{id}/employees")
    public List<EmployeeDto> getCompanyEmployees(@PathVariable long id) {
        return companyService.findCompany(id).getEmployees().stream().map(EmployeeDto::new).toList();
    }

    @GetMapping
    public List<CompanyDto> getAllCompanies() {
        return companyService.findAllCompanies().stream()
                .map(CompanyDto::new)
                .toList();
    }

    @PostMapping
    public CompanyDto create(@RequestBody @Valid CompanyDto companyDto) {
        return new CompanyDto(companyService.addCompany(companyDto.getName()));
    }

    @PutMapping("/{id}")
    public CompanyDto update(@PathVariable Long id,
                             @RequestBody @Valid CompanyDto companyDto) {
        return new CompanyDto(companyService.updateCompany(id, companyDto.getName()));
    }

    @DeleteMapping("/{id}")
    public CompanyDto delete(@PathVariable Long id) {
        return new CompanyDto(companyService.deleteCompany(id));
    }

    @PutMapping("/{id}/hire")
    public EmployeeDto hire(@PathVariable Long id, @RequestParam Long employeeId) {
        Employee e = employeeService.findEmployee(employeeId);
        return new EmployeeDto(companyService.addNewEmployee(id, e));
    }

    @PutMapping("/{id}/dismiss")
    public EmployeeDto dismiss(@PathVariable Long id, @RequestParam Long employeeId) {
        Employee e = employeeService.findEmployee(employeeId);
        return new EmployeeDto(companyService.deleteEmployee(id, e));
    }

}
