DROP TABLE IF EXISTS Tickets;
DROP TABLE IF EXISTS Flights;
DROP TABLE IF EXISTS Airports;
DROP TABLE IF EXISTS Users;
DROP TABLE IF EXISTS Passengers;

CREATE TABLE Passengers (
    ID BIGINT PRIMARY KEY,
    `Name` VARCHAR(255) NOT NULL,
    Phone_number BIGINT NOT NULL,
    CHECK (REGEXP_LIKE(ID, '^\\d{18}$')),
    CHECK (REGEXP_LIKE(Phone_number, '^\\d{11}$'))
);

CREATE TABLE Users (
    Phone_number BIGINT PRIMARY KEY,
    Username VARCHAR(255) NOT NULL,
    `Password` VARCHAR(255) NOT NULL,
	CHECK (REGEXP_LIKE(Phone_number, '^\\d{11}$'))
);

CREATE TABLE Airports (
    ID INT AUTO_INCREMENT PRIMARY KEY,
    `Name` VARCHAR(255) UNIQUE NOT NULL,
    Country VARCHAR(255) NOT NULL,
    City VARCHAR(255) NOT NULL
);

CREATE TABLE Flights (
    ID VARCHAR(255) PRIMARY KEY,
    Airline VARCHAR(255) NOT NULL,
    Departure_airport INT NOT NULL,
    Arrival_airport INT NOT NULL,
    Departure_time DATETIME NOT NULL,
    Arrival_time DATETIME NOT NULL,
    First_class_seats_remaining INT NOT NULL, -- 头等舱剩余座位
    Business_class_seats_remaining INT NOT NULL, -- 商务舱剩余座位
    Economy_class_seats_remaining INT NOT NULL, -- 经济舱剩余座位
    First_class_price DECIMAL(7, 2) NOT NULL, -- 头等舱价格
    Business_class_price DECIMAL(7, 2) NOT NULL, -- 商务舱价格
    Economy_class_price DECIMAL(7, 2) NOT NULL, -- 经济舱价格
    `Status` VARCHAR(255) NOT NULL CHECK (`Status` IN ('候机中', '延误', '已起飞', '已降落', '开始检票')), -- 航班状态
    FOREIGN KEY (Departure_airport) REFERENCES Airports(ID) ON DELETE CASCADE,
    FOREIGN KEY (Arrival_airport) REFERENCES Airports(ID) ON DELETE CASCADE,
    CHECK (Departure_time < Arrival_time)
);

CREATE TABLE Tickets (
    ID INT AUTO_INCREMENT PRIMARY KEY,
    Price DECIMAL(7, 2) NOT NULL,
    FlightID VARCHAR(255) NOT NULL,
    Seat_class VARCHAR(255) NOT NULL, -- 级别信息
    PassengerID BIGINT NOT NULL,
    Paid TINYINT NOT NULL,
    FOREIGN KEY (FlightID) REFERENCES Flights(ID) ON DELETE CASCADE,
    FOREIGN KEY (PassengerID) REFERENCES Passengers(ID) ON DELETE CASCADE,
    CHECK (Seat_class IN ('First Class', 'Business Class', 'Economy Class'))
);