package com.kym.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.kym.common.R;
import com.kym.common.exception.BusinessException;
import com.kym.entity.miniapp.InvoiceTitle;
import com.kym.service.miniapp.InvoiceTitleService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/invoice/title")
public class InvoiceTitleController {

    private final InvoiceTitleService invoiceTitleService;

    public InvoiceTitleController(InvoiceTitleService invoiceTitleService) {
        this.invoiceTitleService = invoiceTitleService;
    }

    @GetMapping("/list")
    R<?> list() {
        var userId = StpUtil.getLoginIdAsLong();
        return R.success(invoiceTitleService.listByUser(userId));
    }

    @GetMapping("/{id}")
    R<?> getById(@PathVariable Long id) {
        var title = invoiceTitleService.getById(id);
        if (title == null) {
            throw new BusinessException("抬头不存在");
        }
        return R.success(title);
    }

    @PostMapping
    R<?> create(@RequestBody InvoiceTitle title) {
        title.setId(null);
        title.setUserId(StpUtil.getLoginIdAsLong());
        invoiceTitleService.saveTitle(title);
        return R.success(title);
    }

    @PutMapping("/{id}")
    R<?> update(@PathVariable Long id, @RequestBody InvoiceTitle title) {
        var existing = invoiceTitleService.getById(id);
        if (existing == null) {
            throw new BusinessException("抬头不存在");
        }
        title.setId(id);
        title.setUserId(existing.getUserId());
        invoiceTitleService.updateById(title);
        return R.success();
    }

    @DeleteMapping("/{id}")
    R<?> delete(@PathVariable Long id) {
        invoiceTitleService.removeById(id);
        return R.success();
    }

    @PostMapping("/{id}/delete")
    R<?> deleteByPost(@PathVariable Long id) {
        invoiceTitleService.removeById(id);
        return R.success();
    }

    @PutMapping("/{id}/default")
    R<?> setDefault(@PathVariable Long id) {
        var title = invoiceTitleService.getById(id);
        if (title == null) {
            throw new BusinessException("抬头不存在");
        }
        invoiceTitleService.setDefault(title.getUserId(), id);
        return R.success();
    }
}
