-- 创建数据库（如需）
-- CREATE DATABASE book_management;

-- 切换数据库
-- \c book_management

-- 作者表
CREATE TABLE author
(
    author_id   SERIAL PRIMARY KEY,
    name        VARCHAR(100) NOT NULL,
    nationality VARCHAR(50)
);

-- 出版社表
CREATE TABLE publisher
(
    publisher_id SERIAL PRIMARY KEY,
    name         VARCHAR(100) NOT NULL UNIQUE,
    address      VARCHAR(200)
);

-- 图书表
CREATE TABLE book
(
    book_id      SERIAL PRIMARY KEY,
    title        VARCHAR(200)   NOT NULL,
    isbn         VARCHAR(20)    NOT NULL UNIQUE,
    price        NUMERIC(10, 2) NOT NULL CHECK (price >= 0),
    stock        INT            NOT NULL CHECK (stock >= 0),
    publish_date DATE,
    publisher_id INT            NOT NULL REFERENCES publisher (publisher_id)
);

-- 图书作者关联表（多对多）
CREATE TABLE book_author
(
    book_author_id SERIAL PRIMARY KEY,
    book_id        INT NOT NULL REFERENCES book (book_id) ON DELETE CASCADE,
    author_id      INT NOT NULL REFERENCES author (author_id) ON DELETE CASCADE
);

-- 读者表
CREATE TABLE reader
(
    reader_id SERIAL PRIMARY KEY,
    username  VARCHAR(50)  NOT NULL UNIQUE,
    password  VARCHAR(100) NOT NULL,
    email     VARCHAR(100) NOT NULL UNIQUE,
    is_admin  BOOLEAN      NOT NULL DEFAULT FALSE,
    is_banned BOOLEAN      NOT NULL DEFAULT FALSE,
    phone     VARCHAR(20)
);

-- 订单表
CREATE TABLE orders
(
    order_id     SERIAL PRIMARY KEY,
    reader_id    INT            NOT NULL REFERENCES reader (reader_id),
    order_date   TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    total_amount NUMERIC(10, 2) NOT NULL CHECK (total_amount >= 0),
    status       VARCHAR(20)    NOT NULL
);

-- 订单项表
CREATE TABLE order_item
(
    order_item_id SERIAL PRIMARY KEY,
    order_id      INT            NOT NULL REFERENCES orders (order_id) ON DELETE CASCADE,
    book_id       INT            NOT NULL REFERENCES book (book_id),
    quantity      INT            NOT NULL CHECK (quantity > 0),
    unit_price    NUMERIC(10, 2) NOT NULL CHECK (unit_price >= 0)
);